What is the error in this code? - database

I want to delplay the row in the richtextbox
private void button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection("Data Source=MOSTAFA\\SQLEXPRESS;Initial Catalog=company;Integrated Security=True");
SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"')",con);
con.Open();
SqlDataReader read = com.ExecuteReader();
if (read.Read())
richTextBox1.Text = "id" + read[0].ToString();
else
label3.Text=("The client didn't found");
}

There's an error in your generated query. You have a closing parenthesis without an opening one. The line as you have it would produce:
select * from data where id='sometest')
which will yield a syntax error from SQL Server.
Try this instead:
SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"'",con);

You have an extra parenthesis in that SQL statement.
But more importantly, you are leaving yourself wide open for SQL Injection. To get around this devastating and easily avoidable issue is to use parameterized queries.

Related

Perform SUM query in ADO.NET

I am getting following error
;expected
I am trying to find sum of column values in my webform.
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select SUM("AMOUNT DEPOSITED ") From MAIN_TABLE6";
Double amount = cmd.ExecuteScalar();
Label3.Text = amount.ToString();
}
Use brackets to enclose your columns in SQL Server.
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6";
Double amount = cmd.ExecuteScalar();
Label3.Text = amount.ToString();
}
I update-voted the answer by #ϻᴇᴛᴀʟ because he solved the problem with the brackets. However I like to see that database objects are closed and disposed. If database objects are kept local to the methods where they are used then using blocks accomplish this even if there is and error.
It is possible to pass the connection string directly to the constructor of the connection and pass the command text and connection to the constructor of the command. CommandType.Text is the default value so it is not necessary to set it.
I have opened the connection directly before the .Execute... and it is closed immediately after. The user interface is not updated until the connection is closed.
protected void Page_Load(object sender, EventArgs e)
{
double amount;
using (SqlConnection con = new SqlConnection("Your connection string"))
using (SqlCommand cmd = new SqlCommand("Select SUM([AMOUNT DEPOSITED]) From MAIN_TABLE6;", con))
{
con.Open();
amount = (double)cmd.ExecuteScalar();
}
Label3.Text = amount.ToString();
}

SqlDataReader Close and SqlConnection

What happens with the connection in this case? I don't know if reader.Close() close the open sqlconnection.
private static void ReadOrderData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
reader.Close() won't close the SqlConnection, but since you have a using statement, once you exit the using block the connection will get closed anyway.
Closing the reader will not alter the state of the connection. If you did want to do this you can pass CommandBehavior.CloseConnection to the ExecuteReader method of the SqlCommand instance.
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
It is recommended you put a using block around all your disposable types like your SqlDataReader instance.
using(SqlDataReader reader = command.ExecuteReader()) {
// rest of code
}
See also CommandBehavior for more options.
Check Connection State
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
connection.Open();
And since you are doing
using (SqlConnection connection =
new SqlConnection(connectionString))
{
this will make sure connection is disposed as it inherits from IDisposable despite Exception. And object are disposed once they exit their corresponding scope.
And better use
using(SqlCommand command = new SqlCommand(queryString, connection))
and
using(SqlDataReader reader = command.ExecuteReader())
for the same reason mentioned above.

Local SQL Server connection fail

I'm trying to connect to a local SQL Server database file and do not know if connection string is right:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
DataSet myDataSet = new DataSet();
sda.Fill(myDataSet);
I have such code wrapped in a try catch and always throws this exception:
Reference to object not established as an instance of an object
What's wrong?
EDIT:
Sorry, I have been commenting code to see what line arises such error and it's the following:
DataRowCollection drc = myDataSet.Tables["plataforms"].Rows;
Sorry, I made a wrong question.
I think You must open connection before Fill
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = sda;
DataSet myDataSet = new DataSet();
try {
con.Open();
sda.Fill(myDataSet);
} catch (Exception ex) {
throw (ex);
} finally {
con.Close();
}
you can try this code.

An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'.'

My code:
string SqlSelectQuery = " Select * From [KTS MANAGMENT] Where STAFF NAME=" + Convert.ToString(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
I get this error:
An expression of non-boolean type specified in a context where a condition is expected, near 'NAME'
You should always use parametrized queries to avoid SQL injection - still the #1 vulnerability in computing.
Thus, your code should be something like this:
string connectionString = "......"; // typically read from config file
string query = "SELECT * FROM [KTS MANAGMENT] WHERE STAFF NAME = #Name";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con)
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = textBox1.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
// read the values from the SQL data reader....
}
con.Close();
}
This approach also avoid the error you have with missing and/or mismatched single or double quotes around strings in a SQL statement ...

Inserting a single row with large number of columns in SQL Server

I have a huge form that has around 110 fields columns (single row) that need to be saved in a database.
What is the best approach to insert these many columns into the database using ADO.NET?
I don't think I should be using an insert statement like this, since the query would be very large due to the number of fields.
conn.Open();
string insertString = #"
insert into Categories (CategoryName, Description)
values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
I think of dumping the data into temp file and then adding them into a datatable and then inserting them into database using SqlBulkCopy.
Is there a better approach? How would you handle this situation?
I am afraid there isn't a good shortcut for inserting this number of columns, but using parameters will likely save some debugging time. By using parameters you do not need to worry about things likes apostrophes in strings and type conversions. Here's a sample:
public static void TryThis()
{
try
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "YourConnectionString";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Categories (CategoryName, Description) VALUES (#CategoryName, #Description)";
cmd.Parameters.AddWithValue("CategoryName", "Miscellaneous");
cmd.Parameters.AddWithValue("Description", "Whatever doesn't fit elsewhere");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Resources