SQL Server 2014:Where 附近的语法不正确

SQL Server 2014: incorrect syntax near Where

我使用 Visual Studio 2013 和 SQL Server 2014。我收到一个错误

Incorrect syntax near 'Where Ad= '

我是初学者,所以我无法找出问题所在,需要您的帮助。

这是我的代码:

private void btngno_Click(object sender, EventArgs e)
{
    SqlConnection baglan = new SqlConnection("Server=.;Database=lalala;Trusted_Connection=true;");
    baglan.Open();

    SqlCommand cmd2 = new SqlCommand("UPDATE ilktablom SET gno= " + Int32.Parse(gnotxt.Text) + "'Where Ad= '" + txtAd.Text + "' ,Soyad= '" + txtSoyad.Text + "' ,Sifre= '" + txtSifre.Text, baglan);
    if (cmd2.ExecuteNonQuery() == 1)
    {
        MessageBox.Show("Process completed.");
    }
    else
    {
        MessageBox.Show("Process not completed.");
    }
}     

错误文本不言自明。

你的语法确实不正确:

Where Ad= '" + txtAd.Text + "' ,Soyad= '.....

这个连接产生类似

的查询
Where Ad='something', Soyad = 'something'..., 

但在Sql中,服务器条件应该使用andor和其他逻辑运算符连接,而不是逗号。

所以它应该类似于(也许不是 and 但应该使用 or 运算符 - 从上下文中不清楚)。

Where Ad='something' and Soyad = 'something'..., 

另请注意,连接您的查询文本会使您无法防御 sql 注入。考虑改用 parameterized 查询。

您正在生成的 SQL(除了对 SQL 注入开放之外)缺少终止符 ',并且在 WHERE 子句中使用逗号(而不是 AND

相反,您可以这样做:

private void btngno_Click(object sender, EventArgs e)
{
    using (SqlConnection baglan = new SqlConnection("Server=.;Database=lalala;Trusted_Connection=true;"))
    {
        baglan.Open();

        using (SqlCommand cmd2 = new SqlCommand("UPDATE ilktablom SET gno = @gno Where Ad = @Ad AND Soyad= @Soyad AND Sifre = @Sifre", baglan))
        {
            cmd2.Parameters.Add("@gno", SqlDbType.Int).Value = gnotxt.Text;
            cmd2.Parameters.Add("@Ad", SqlDbType.Varchar).Value = txtAd.Text;
            cmd2.Parameters.Add("@Soyad", SqlDbType.Varchar).Value = txtSoyad.Text;
            cmd2.Parameters.Add("@Sifre", SqlDbType.Varchar).Value = txtSifre.Text;
            if (cmd2.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("Process completed.");
            }
            else
            {
                MessageBox.Show("Process not completed.");
            }
        }
    }
}