's'附近的语法不正确

时间:2014-10-29 07:23:54

标签: c# sql .net

我在sc.ExecuteNonQuery();上收到错误。错误:Incorrect syntax near 's'

代码:

con = new SqlConnection("Data Source=DELL-PC;Initial Catalog=sashi;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Login VALUES('" + textBoxUID.Text + "','" + textBoxPWD.Text + "','" + comboBoxQUN.Text + "','" + textBoxANS.Text + "' ) ", con);

sc.ExecuteNonQuery();
MessageBox.Show("Record has been inserted");

con.Close();

我忘记了什么或错误在哪里?

1 个答案:

答案 0 :(得分:1)

请使用以下参数:

using (var con = new SqlConnection("Data Source=DELL-PC;Initial Catalog=sashi;Integrated Security=True")) 
{
    con.Open(); 
    using(var sc = connection.CreateCommand()) 
    { 
        sc.CommandText = "INSERT INTO Login VALUES(@uid,@pass,@qun,@ans)";  

        sc.Parameters.Add(new SqlParameter("@uid", textBoxUID.Text));
        sc.Parameters.Add(new SqlParameter("@pass", textBoxPWD.Text));
        sc.Parameters.Add(new SqlParameter("@qun", comboBoxQUN.Text));
        sc.Parameters.Add(new SqlParameter("@ans", textBoxANS.Text));;  

        sc.ExecuteNonQuery(); 
    } 
}

Sql参数有助于防止SQL注入攻击..并且更容易阅读.. 您的登录表只有四列吗?否则你还必须在insert语句中指定它:INSERT INTO (col1, col2 ....