Home > Mobile >  What is the reason for my SqlException: Incorrect syntax near '='? [closed]
What is the reason for my SqlException: Incorrect syntax near '='? [closed]

Time:10-04

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 '='."

CodePudding user response:

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.Int, 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();

CodePudding user response:

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.

CodePudding user response:

I think the problem is because you don't have ' in the quotes, try this and check if it works

cmd.CommandText = "select * from teacher where tID = '"   textBox1.Text   "'";
  • Related