我想要删除数据库的记录。我想先检查这条记录是否存在,是否存在继续,但是如果不存在,则显示带有消息框的消息。我不知道如何设置此检查。任何想法?这是我的代码:
if (textBoxCode.Text != String.Empty && textBoxLastName.Text != String.Empty && textBoxFirstName.Text != String.Empty)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Student where Code='" + textBoxCode.Text + "' and Last_Name='" + textBoxLastName.Text + "' and First_Name='" + textBoxFirstName.Text + "'";
cmd.ExecuteNonQuery();
con.Close();
DisplayData();
MessageBox.Show("Student deleted successfully", "Delete Done", MessageBoxButtons.OK);
textBoxCode.Text = String.Empty;
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
}
答案 0 :(得分:2)
您可以使用ExecuteNonQuery
函数的返回值。
if (textBoxCode.Text != String.Empty && textBoxLastName.Text != String.Empty && textBoxFirstName.Text != String.Empty)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from Student where Code=@Code and Last_Name=@Last_Name and First_Name=@First_Name";
cmd.Parameters.AddWithValue("@Code", textBoxCode.Text);
cmd.Parameters.AddWithValue("@Last_Name", textBoxLastName.Text);
cmd.Parameters.AddWithValue("@First_Name", textBoxFirstName.Text);
int rc = cmd.ExecuteNonQuery();
if (rc > 0)
{
MessageBox.Show("Student deleted successfully", "Delete Done", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("There is no record found for delete!", "Delete Done", MessageBoxButtons.OK);
}
con.Close();
DisplayData();
textBoxCode.Text = String.Empty;
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
}