如果数据不存在则更新错误

Update error if data does not exist

观看视频后,我设法用 SQL 创建了自己的 "save, update, delete" 程序。

我有一个问题,如果我在数据库中没有 "IndexNumber" 的情况下单击 "update",则不会发生任何事情。

任何人都可以建议我如何改进我的 "update" 按钮吗?也许如果数据不存在,程序可以用一个消息框提示用户而不是什么都不做。喜欢"IndexNumber does not exist therefore unable to update"

我的更新码

SqlConnection con = new SqlConnection(
    @"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + 
    "\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(@"UPDATE GlennTeoStudents SET IndexNumber = '" + 
    numIN.Value + "',Name = '" + txtName.Text + "',Age ='" + txtAge.Text + 
    "',HandPhoneNumber = '" + txtHP.Text + "',GPA = '" + numGPA.Value + 
    "' WHERE (IndexNumber='" + numIN.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
 try
{
.....
 con.Open();
SqlCommand cmd = new SqlCommand(@"Select count(*) from GlennTeoStudents
                         WHERE (IndexNumber='" + numIN.Value + "')", con);

    int count1 = cmd.ExecuteScalar();

    if (count1 != 0)
      {
    do your update
    }
    else
    {
     give your message box
    }

    }

SqlCommand.ExecuteNonQuery() returns 受影响的行数 (int)。 您可以查看 return 值:

SqlCommand.ExecuteNonQuery(asd)
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (!(rowsAffected > 0))
{
    throw new ArgumentException(<Your Message>);
}

然后只要在调用该方法的任何地方捕获异常并使用

显示您的消息框
MessageBox.Show(<Your Message>)