C#中的SQL更新语句 [英] SQL update statement in C#

查看:178
本文介绍了C#中的SQL更新语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表学生

   P_ID   LastName  FirstName  Address  City

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

如何在C#中更改编辑代码

How do i change edit code in 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();
 } 

编辑其中 Lastname 字段具有姓氏值的条目并且名字字段具有名字值。

to edit entry where Lastname field has lastname value and FirstName field has firstname value.

我不想这样使用

 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+"'";

但是该语句没有得到执行,为什么会抛出SQL异常?

but the statement is not getting executed, why is it throwing SQL exception ? Is there nay solution to it ?

推荐答案

这不是更新SQL中记录的正确方法:

This is not a correct method of updating record in SQL:

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

您应该这样写:

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.

这篇关于C#中的SQL更新语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆