简体   繁体   English

C#中的SQL更新语句

[英]SQL update statement in C#

I have table "Student"我有表“学生”

   P_ID   LastName  FirstName  Address  City

   1        Hansen    Ola                
   2        Svendson   Tove
   3        Petterson   Kari
   4        Nilsen       Johan
...and so on 

How do i change edit code in C#如何更改 C# 中的编辑代码

 string firstName = "Ola";
 string  lastName ="Hansen";
 string  address = "ABC";
 string city = "Salzburg";

 string connectionString = System.Configuration.ConfigurationManager
                          .ConnectionStrings["LocalDB"].ConnectionString;

 using (SqlConnection connection = new SqlConnection(connectionString))
     using (SqlCommand command = connection.CreateCommand())
 { 
   command.CommandText = "INSERT INTO Student (LastName, FirstName, Address, City) 
                          VALUES (@ln, @fn, @add, @cit)";

   command.Parameters.AddWithValue("@ln", lastName);
   command.Parameters.AddWithValue("@fn", firstName);
   command.Parameters.AddWithValue("@add", address);
   command.Parameters.AddWithValue("@cit", city);

   connection.Open();

   command.ExecuteNonQuery();

   connection.Close();
 } 

to edit entry where Lastname field has lastname value and FirstName field has firstname value.编辑Lastname字段具有 lastname 值且FirstName字段具有 firstname 值的条目。

I dont want to use like this我不想这样使用

 UPDATE Persons  SET Address='Nissestien 67', City='Sandnes' 
 WHERE LastName='Tjessem'     AND FirstName='Jakob'

and i edited my original statement to我将我原来的声明编辑为

 command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) 
   VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + 
                           "' AND FirstName='" +  firstName+"'";

but the statement is not getting executed, why is it throwing SQL exception ?但是语句没有被执行,为什么会抛出 SQL 异常? Is there nay solution to it ?有没有解决办法?

This is not a correct method of updating record in SQL: 这不是更新SQL中记录的正确方法:

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";

You should write it like this: 你应该这样写:

command.CommandText = "UPDATE Student 
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";

Then you add the parameters same as you added them for the insert operation. 然后添加与为插入操作添加的参数相同的参数。

I dont want to use like this 我不想这样用

That is the syntax for Update statement in SQL , you have to use that syntax otherwise you will get the exception. 这是SQL中Update语句的语法 ,您必须使用该语法,否则您将获得异常。

command.Text = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn AND LastName = @ln";

and then add your parameters accordingly. 然后相应地添加您的参数。

command.Parameters.AddWithValue("@ln", lastName);
command.Parameters.AddWithValue("@fn", firstName);
command.Parameters.AddWithValue("@add", address);
command.Parameters.AddWithValue("@cit", city);  

如果您不想使用SQL语法(您不得不使用),那么请切换到Entity Framework或Linq-to-SQL之类的框架,您不需要自己编写SQL语句。

There is always a proper syntax for every language. 每种语言都有适当的语法。 Similarly SQL(Structured Query Language) has also specific syntax for update query which we have to follow if we want to use update query. 类似地,SQL(结构化查询语言)也具有更新查询的特定语法,如果我们想要使用更新查询,我们必须遵循这些语法。 Otherwise it will not give the expected results. 否则它不会给出预期的结果。

string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account  SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();

Please, never use this concat form: 请永远不要使用这个连续形式:

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
        + "WHERE supplier_id = " + textBox1.Text;

use: 使用:

command.Parameters.AddWithValue("@attribute", value);

Always work object oriented 始终以工作为导向

Edit: This is because when you parameterize your updates it helps prevent SQL injection. 编辑:这是因为当您参数化更新时,它有助于防止SQL注入。

command.Text = "UPDATE Student 
  SET Address = @add, City = @cit
  Where FirstName = @fn and LastName = @add";

private void button4_Click(object sender, EventArgs e)
    {
        String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("刪除成功");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }



    private void button6_Click(object sender, EventArgs e)
    {
        String st = "SELECT * FROM suppliers";

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            SqlDataReader reader = sqlcom.ExecuteReader();
            DataTable datatable = new DataTable();
            datatable.Load(reader);
            dataGridView1.DataSource = datatable;
            //MessageBox.Show("LEFT OUTER成功");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

If you are using EF Core , then you can use FromSqlRaw Here is an example.如果您使用的是 EF Core ,那么您可以使用 FromSqlRaw 这是一个示例。

Using Robin's update string, Just add SELECT STATEMENT At the end.使用 Robin 的更新字符串,只需在末尾添加 SELECT STATEMENT。

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text + "WHERE supplier_id = " + textBox1.Text;字符串 st = "更新供应商 SET 供应商 ID = " + textBox1.Text + ",供应商名称 = " + textBox2.Text + "WHERE 供应商 ID = " + textBox1.Text; SELECT Id From supplier WHERE supplier_Id ="+ textBox1,Text从供应商那里选择 ID WHERE supplier_Id =“+ textBox1,Text

var updatedSupplier = context.Supplier.FromSqlRaw(st).ToList(); var updatedSupplier = context.Supplier.FromSqlRaw(st).ToList();

(Please note this is using EF Core , Data table has Id column ) (请注意这是使用 EF Core ,数据表有 Id 列)

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text
            + "WHERE supplier_id = " + textBox1.Text;

        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("update successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }

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

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