且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果数据库中的值不存在,如何显示错误消息

更新时间:2022-11-26 08:29:25

要插入,请使用以下查询...
To insert, you are using the below query...
cmd.CommandText = "if exists (select * from phonebook) delete phonebook where NAME=@NAME;";


但是在此之前,您想检查一下它是否确实存在.为此,您必须运行另一个查询以查看其是否存在.您可以使用COUNT().


But before that, you want to check if that really exists or not. For that, you have to run another query to see if it exists or not. You can use COUNT().

cmd.CommandText = "select count(someColumnName) from phonebook where NAME=@NAME;";


现在,使用SqlDataReader SqlAdapter ExecuteScalar 方法读取所选值.如果是> 0,则名称存在.

注意:将现有的列名替换为"someColumnName".


Now, use SqlDataReader or SqlAdapter or ExecuteScalar method to read the selected value. If that is > 0, then the name exists.

Note: Replace your existing Column Name for "someColumnName".


首先获取计数并显示消息(如果不存在),否则继续删除. :-)
get the count first and show the message if not exist, otherwise proceed with delete.. :-)
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
    cn.Open();

    using (SqlCommand commandRowCount
        = new SqlCommand("SELECT COUNT(*) FROM phonebook where NAME=@NAME", cn))
    {
        commandRowCount.Parameters.AddWithValue("@NAME", name);
        var countStart = (int)commandRowCount.ExecuteScalar();

        if(countStart< 1)
        {
            MessageBox.Show("Name doesnot exists in database");
            return;
        }
    }
    using (SqlCommand cmdDel
        = new SqlCommand("delete phonebook where NAME=@NAME", cn))
    {
        cmdDel.Parameters.AddWithValue("@NAME", name);
        cmdDel.ExecuteNonQuery();
        MessageBox.Show("values deleted");
    }
}


删除名称之前,请先使用where条件名称选择数据;

然后将数据放入数据表

然后

Before deleting a name 1st u select the data using where condition name;

then put the data in datatable

then

 if(datatable.rows.count>0)
 {
    Your delete query 
 } 

 else
{
  your message;
}