此代码放在按钮中。当我点击它来更新数据时,会出现一个消息框错误,说明"命令执行期间遇到致命错误"。
你的答案会很有帮助。谢谢
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
try
{
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_offense SET TYPE=@TYPE,DATE_HAPPENED=@DH,DESCRIPTION=@DESC,SANCTION=@SANC" +
"Where STUDENT_NO = @STUDENT_NO And DESCRIPTION=@DESC And SANCTION=@SANC And DATE_HAPPENED=@DH";
cmd.Parameters.AddWithValue("@TYPE", offense_combo.Text);
cmd.Parameters.AddWithValue("@DH", date_hapen.Text);
cmd.Parameters.AddWithValue("@DESC", description_txt.Text);
cmd.Parameters.AddWithValue("@SANC", sanction_txt.Text);
cmd.Parameters.AddWithValue("@STUDENT_NO", studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
MessageBox.Show("updated");
//refresh
cmd.CommandText = "SELECT student_info.Student_no,student_info.Lastname,student_info.Firstname,student_offense.Type,student_offense.Description,student_offense.Date_Happened,student_offense.Sanction,student_offense.Date_Recorded from student_info,student_offense where student_info.student_no = student_offense.student_no";
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
student_no_valid.Visible = false;
stud_no_error.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listBox1.Items.Clear();
description_txt.Text = "";
studentNo_txt.Text = "";
offense_combo.Text = "";
current_date();
sanction_txt.Text = "";
答案 0 :(得分:2)
您在参数@SANC
和Where
之间缺少空格。
试试这个:
cmd.CommandText = "UPDATE student_offense SET TYPE=@TYPE,DATE_HAPPENED=@DH,
DESCRIPTION=@DESC,SANCTION=@SANC" + " Where STUDENT_NO = @STUDENT_NO And
DESCRIPTION=@DESC And SANCTION=@SANC And DATE_HAPPENED=@DH";
建议:如果您的DATE_HAPPENED
列类型为Date
,那么您需要发送正确的Date
格式。
试试这个:假设用户以dd-MM-yyyy
格式输入日期。
DateTime dt = DateTime.ParseExact(date_hapen.Text,"dd-MM-yyyy",
CutureInfo.InvariantCulture);
现在,在分配DATE_HAPPENED
值时,提供以下格式
cmd.Parameters.AddWithValue("@DH",dt.ToString("yyyy-MM-dd"));
答案 1 :(得分:0)
可能这发生在cmd.ExecuteNonQuery();
或后续查询中。您可以在断点后单步执行验证。 SQL中可能存在错误。您可以通过查看内部错误或在MySQL Workbench上尝试查询来找到它。检查所有参数是否与表列匹配,并且所有数据类型都匹配。
顺便说一句,不需要在update语句中指定SANCTION和DATE_HAPPENED,因为在WHERE中要求它们相等。