简体   繁体   English

SQL查询(C#)中的更新语句

[英]SQL query for update statement in (C#)

I am new to the C# programming. 我是C#编程的新手。 Facing the problem Incorrect syntax near 'First_Name'.! 面对问题'First_Name'附近的语法不正确。 in the given below code: 在下面的代码中:

private void button2_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
        con.Open();
        if (con.State == System.Data.ConnectionState.Open)
        {
            SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
            //'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
            cmd.Connection = con;
            cmd.CommandType = System.Data.CommandType.Text;
            int a = cmd.ExecuteNonQuery();
            if (a > 0)
            {
                MessageBox.Show("You Have Successfully Updated");
                Custid.Text = "";
                fname.Text = "";
                lname.Text = "";
                address.Text = "";
                contact.Text = "";
                email.Text = "";
                landmark.Text = "";
                deposite.Text = "";
            }
        }     
    }

Problem : You forgot to add word SET after your table name in update statement. 问题:您忘记在更新语句中的表名后添加单词SET

Solution1 : Add the word SET after table name in Update query (Don't Recommend this) 解决方案1:在更新查询中的表名后添加单词SET (不推荐这样做)

"update Customer_Info SET First_Name ='" + fname.Text + "'"

Warning : Your query is open to sql injection attacks .please use parameterised queries to avoid them 警告:您的查询对sql注入攻击开放。请使用参数化查询来避免它们

Solution 2: Using Parameterised Queries 解决方案2:使用参数化查询

Replace This: 替换为:

SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name 
                                                             ='"+fname.Text+"'");

With This: 有了这个:

SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = @fname");
cmd.Parameters.AddWithValue("@fname" , fname.Text);

您的问题不在C#,SQL语法中(您错过了set关键字)

SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

you are missing SET keyword: 您缺少SET关键字:

update Customer_Info SET First_Name ='" + fname.Text + "'"

and also provide where clause otherwise it will update all the records in your table. 并提供where子句,否则它将更新表中的所有记录。

您在查询中缺少set关键字,您必须像这样放置set

SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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