使用C#中的SQL参数更新数据

时间:2016-12-06 08:08:58

标签: c# sql-server

我有一个关于使用SqlParameter和类...

进行更新的问题

在我的班级EditRecord中:

string strScript = "";
strScript = strScript + "UPDATE tbMemberInfo(FirstName,LastName,Age)";
strScript = strScript + "SET (FirstName = @firstname, LastName = @lastname, Age = @age)";
strScript = strScript + "WHERE id=@empID";

SqlCommand cmd;
cmd = new SqlCommand(strScript, Connection);
cmd.CommandTimeout = 0;

cmd.Parameters.AddWithValue("@firstname", _members.Lastname));
cmd.Parameters.AddWithValue("@lastname", _members.FirstName));
cmd.Parameters.AddWithValue("@age", _members.Age));
cmd.Parameters.AddWithValue("@empID", _members.ID));
cmd.ExecuteNonQuery();

在我的表格中调用课程

Class.clsMemberInfo member = new Class.clsMemberInfo();

member.FirstName = txtFirstName.Text;
member.Lastname = txtLastName.Text;
member.Age = Convert.ToInt32(txtAge.Text);

clsMembers memberInfo = new clsMembers();

memberInfo.Members = member;
memberInfo.EditREcord(cnTestConnection);
MessageBox.Show("Success");

但是数据没有更新

1 个答案:

答案 0 :(得分:1)

将sql语句更改为

string strScript = "UPDATE tbMemberInfo SET FirstName = @firstname, LastName = @lastname, Age = @age WHERE id=@empID";

更新语法是

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

表名

旁边的()中没有给出列名

<强>更新

在调用方法

之前,未在代码_members.ID中设置

Class.clsMemberInfo member = new Class.clsMemberInfo();

member.FirstName = txtFirstName.Text;
member.Lastname = txtLastName.Text;
member.Age = Convert.ToInt32(txtAge.Text);
member.ID  = ??? //you need to give this value, otherwise your update will not work