c#中如何对指定的数据进行修改

来源:百度知道 编辑:UC知道 时间:2024/09/23 03:44:55
想通过对指定的学号(ID)的姓名进行修改
SqlConnection conn=new SqlConnection ("server=localhost;database=testmode;Integrated Security=SSPI");
conn.Open();
string updaterCmd = "Update student set name=@name";
SqlCommand myCommand=new SqlCommand
(updaterCmd ,conn);

myCommand.Parameters .Add(new SqlParameter("@name",SqlDbType.Text,16));
myCommand.Parameters["@name"].Value=txtName.Text;
myCommand.ExecuteNonQuery();

myCommand.Connection.Close();
运行的时候结果所有的姓名都改了
仔细一看 得给指定的name 我知道查询的限制语句是 select name form student where ID=txtID.Text(从输入的ID号进行修改)
初学 。。。所不知道如何修改

SqlConnection conn=new SqlConnection ("server=localhost;database=testmode;Integrated Security=SSPI");
conn.Open();
string updaterCmd = "Update student set name=@name where ID=@id";
SqlCommand myCommand=new SqlCommand
(updaterCmd ,conn);

myCommand.Parameters .AddWithValue("@name",txtName.Text);
myCommand.Parameters .AddWithValue("@id",txtID.Text); myCommand.ExecuteNonQuery();

myCommand.Connection.Close();

sql语句错误了
Update student set name=@name
你这个sql语句本身就是更新所有记录
如果想要更新一条记录那么要加条件
Update student set name=@name where id=1
这样的话就更新id为1的记录

明白?
还不明白的话建议你先去学习一下sql的基本语法
这是非常重要的

1、ID是int类型吧, txtID.Text好象是string类型,将txtID.Text转成整数
2、string updaterCmd = "Update student set name=@name where ID=“+txtID.Text;
应该就可以了