C# - 如何通知用户是否已经向mysql插入值
本文关键字:是否 mysql 插入 用户 何通知 通知 | 更新日期: 2023-09-27 18:36:02
是否可以
在 C# 中提醒用户(使用 MessageBox)并return;
他是否将相同的值插入具有唯一约束的列?我在姓氏、名字和中间名中都有唯一的。
String command = "INSERT IGNORE INTO studentstbl (LastName, FirstName, MiddleInitial, Address, Age, Birthday, Gender, Guardian, ContactNumber, Year, IsEnrolled) VALUES (@lastname, @firstname, @middleinitial, @address, @age, @birthday, @gender, @guardian, @contactnumber, @year, 0);";
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.Parameters.AddWithValue("@lastname", lastnametxt.Text);
cmd.Parameters.AddWithValue("@firstname", firstnametxt.Text);
cmd.Parameters.AddWithValue("@middleinitial", middleitxt.Text);
cmd.Parameters.AddWithValue("@address", addresstxt.Text);
cmd.Parameters.AddWithValue("@age", agetxt.Text);
cmd.Parameters.AddWithValue("@birthday", birthdaypicker.Text);
cmd.Parameters.AddWithValue("@gender", gendercmb.Text);
cmd.Parameters.AddWithValue("@guardian", guardiantxt.Text);
cmd.Parameters.AddWithValue("@contactnumber", contactnumtxt.Text);
cmd.Parameters.AddWithValue("@year", yearcmb.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
reset();
MessageBox.Show("Student successfully registered! You can now proceed to Payment to enroll student.");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
您要么必须先运行查询进行检查,要么从查询中删除"IGNORE",以便捕获错误。如果你去掉"IGNORE",你可以捕获更具体的MySqlException并检查错误号。1062 表示存在唯一密钥冲突。MySQL文档有错误号的完整列表。像这样:
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
case 1062:
MessageBox.Show("Name already exists");
}
}
finally
{
//Since you've taken the ignore off you can run whatever you wanted to run here.
}