我有桌子 “学生”
P_ID LastName FirstName Address City 1 Hansen Ola 2 Svendson Tove 3 Petterson Kari 4 Nilsen Johan ...and so on
如何在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(); }
要编辑条目,其中 姓 字段姓价值和 名字 字段名字值。
我不想这样使用
UPDATE Persons SET Address='Nissestien 67', City='Sandnes' WHERE LastName='Tjessem' AND FirstName='Jakob'
然后我将原始声明编辑为
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
但是该语句未得到执行,为什么会引发SQL异常?有没有解决的办法?
这不是更新SQL中记录的正确方法:
您应该这样写:
command.CommandText = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";
然后,添加与为插入操作添加的参数相同的参数。