amandi yalapola
amandi yalapola

Reputation: 5

What is the reason for my SqlException: Incorrect syntax near '='?

This is my code:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "data source = LAPTOP-ULT25NKH; database = college;integrated security = True";

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;

    cmd.CommandText = "select * from teacher where tID = " + textBox1.Text + "";

    DataSet DS = new DataSet();
    SqlDataAdapter DA = new SqlDataAdapter(cmd);
    DA.Fill(DS);

    dataGridView1.DataSource = DS.Tables[0];
}

but I get this exception:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '='."

Upvotes: -3

Views: 830

Answers (2)

Brendan Lesniak
Brendan Lesniak

Reputation: 2321

Ensure you are properly santizing inputs and using prepared statements; to start down the line for you, try:

cmd.CommandText = "SELECT * FROM teacher WHERE tID = @tID;"
SqlParameter idParam = new SqlParameter("@tID", SqlDbType.NVarChar , 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();

Upvotes: 3

Vivek Nuna
Vivek Nuna

Reputation: 1

There are lot of issues in your existing code, I’m mentioning few points brlow.

  1. Please move the connection string to some config file, it’s easy to maintain there.
  2. When you have DataAdapter you don’t need to explicitly open the connection, it does that for you internally.
  3. Please avoid * in select query, mention the columns with alias and use parameterized query to pass the parameters. Or your can write stored procedure and call it. So that I if I’m future you need to modify query, there will be no code change.
  4. If you need to open the connection, please close it or your can use using.
  5. You can add breakpoint and see the value of your query and if you copy this query value and run in sql server directly . This is one way to find the error in the query.

Upvotes: 0

Related Questions