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

时间:2015-05-17 09:22:31

标签: c# sql sql-update

在观看视频后,我设法用SQL创建了自己的“保存,更新,删除”程序。

我有一个问题,如果我点击“更新”而数据库中没有“IndexNumber”,则不会发生任何事情。

有人可以告诉我如何改进我的“更新”按钮吗?也许如果数据不存在,程序可以用消息框提示用户而不是什么都不做。像“IndexNumber不存在因此无法更新”

我的更新代码

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();

2 个答案:

答案 0 :(得分:0)

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

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>)

答案 1 :(得分:-1)

 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
    }

    }