本文介绍了删除记录sql server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

这是我的代码,我在其中通过querry从sql server中删除记录

在表格上,当我单击特定记录以删除该记录时,我具有gridview和两个文本框,首先所有显示在文本框中,然后按删除按钮,它删除记录

但是这里的问题是我想检查记录是否存在,如果数据库中不存在不显示消息记录的话,

如果存在记录,它将重新确认删除记录

这是我的功能



hi to all!

here is my code in which i pass querry to delete record from sql server

on the form i have gridview and two text boxes when i click on particular record to delete that record first ol all display in text boxes and then i press delete button it delete the record

but the problem here is i want to check that record exists their or not if not display message record is not present in data base,

and if record is present the it will re confirm to delete the record

here is my function



{
try
            {
                count = 0;
                int count1 = 0;
                sql_string = ("Data Source=7070270275;Initial Catalog=dsffC;User Id=fssdfadf;Password=fdsfsdfsdf");
                SqlConnection conn = new SqlConnection(sql_string);
                conn.Open();
                SqlCommand command = conn.CreateCommand();
                command.CommandText = (str_querry);
                SqlDataReader rdr = command.ExecuteReader();
                if(rdr.Read())
                count1++;

                if (count1 == 0)
                {
                    MessageBox.Show("There is No Such ID present in Data Base");
                    conn.Close();
                }
                else
                MessageBox.Show("Deleted");
                conn.Close();
                conn.Dispose();
                count++;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("Error in database connection");
            }
        }

推荐答案

int deletedRowsCount = command.ExecuteNonQuery();
if(deletedRowsCount==0)
{
  MessageBox.Show("There is No Such ID present in Data Base");
}
else
{
  MessageBox.Show(deletedRowsCount.ToString() + "rows deleted.");
}


SqlConnection con=new SqlConnection ("connectionstring");
        con.Open ();
        SqlCommand cmd = new SqlCommand("select count(*) from tableName where cid=1233", con);
        int i = 0;
        i=(int)cmd.ExecuteScalar();
        if (i > 0)
        {
            //record is available
            SqlCommand deleteCmd = new SqlCommand("delete tablename where cid=1233", con);
            int res = 0;
            res=deleteCmd.ExecuteNonQuery();
            if (res > 0)
            {
                //deleted successfully
            }
            else
            {
                //failed to delete
            }
        }
        else
        {
            //there is no record
        }


这篇关于删除记录sql server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:35