简体   繁体   中英

SQL Server 2014: incorrect syntax near Where

I use Visual Studio 2013 and SQL Server 2014. I get an error

Incorrect syntax near 'Where Ad= '

I'm a beginner so I couldn't figure out the problem and need your help.

Here is my code:

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.");
    }
}     

Your SQL that you're generating (apart from being open to SQL injection) is missing a terminating ' , and using commas in the WHERE clause (instead of AND )

Instead, you could do something like:

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.");
            }
        }
    }
}  

Error text is self-explanatory.

You are really have incorrect syntax here:

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

This concatenction produces query like

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

but in Sql Server conditions should be joined using and , or and other logical operators, not commas.

So it should be something like (maybe not and but or operator should be used - it is unclear from context).

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

Also note that concatenating your query text makes you defenseless against sql injection. Consider using parameterized query instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM