【发布时间】:2021-03-18 11:25:51
【问题描述】:
当我添加作为 ID 的 WHERE 子句时,在命令执行期间出现致命错误
MySqlCommand MyCommand2 = new MySqlCommand("UPDATE student SET name =@Name, gender = @Gender, course =@Course, section = @Section, violation = @Violation, action = @Action, manual =@Manual, report = @Report, date = @Date ,img = @Img WHERE ID = @id ", MyConn2);
//
MyCommand2.Parameters.AddWithValue("@Name", name_tf.Text);
MyCommand2.Parameters.AddWithValue("@Gender", gender_tf.Text);
MyCommand2.Parameters.AddWithValue("@Course", course_tf.Text);
MyCommand2.Parameters.AddWithValue("@Section", yr_tf.Text);
MyCommand2.Parameters.AddWithValue("@Violation", vio_tf.Text);
MyCommand2.Parameters.AddWithValue("@Action", taken_cb.Text);
MyCommand2.Parameters.AddWithValue("@Manual", manual_tf.Text);
MyCommand2.Parameters.AddWithValue("@Report", report_tf.Text);
MyCommand2.Parameters.AddWithValue("@Date", date_tf.Text);
MyCommand2.Parameters.AddWithValue("@Img", arr);
我的问题是;
- 我的 ID 是不是用户输入的 PK,如何在 where 子句中正确实现它?
- 即使您只选择了特定数据,如何避免更新数据库中的所有数据?
解决!!我是怎么做到的?所以在这里;
int i; // global variable
我把这段代码放在 DataGridView 的属性 CellClick 上
i = Convert.ToInt32(stud_tbl.CurrentRow.Cells[0].Value);
我在mysqlcommand中添加了这个
MyCommand2.Parameters.AddWithValue("@id", i);
谢谢大家的评论!
【问题讨论】:
-
你没有为
@id添加参数值。 -
where 子句 (
WHERE ID = @id) 要求您提供 ID。 -
我还会这样做吗? MyCommand2.Parameters.AddWithValue("@id", 我应该在这里放什么?");
-
我遇到了麻烦,因为@id 不是用户输入,它在我的数据库中自动递增。我应该把参数放在什么地方?
-
您是在向数据库中添加新记录还是要修改您首先从数据库中读取的记录?如果要添加记录,则应使用
INSERT命令。如果您正在从数据库中读取一条记录以便稍后更新它,您需要存储从数据库中出来的ID,并在更新中使用 if。