如何避免在C#中使用windows窗体在SQL Server中插入重复记录

本文关键字:Server 插入 记录 SQL windows 何避免 窗体 | 更新日期: 2023-09-27 17:59:06

在将数据插入客户数据表时,我想问一下,客户id、联系人无电子邮件应该不相同。它应该显示一个消息框,特定记录已经存在于以下代码中:

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=HP'SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
        con.Open();
        if (con.State == System.Data.ConnectionState.Open)
        {
            SqlCommand cmd = new SqlCommand("insert into Customer_Info values('" + Custid.Text.ToString() + "','" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
            cmd.Connection = con;
            cmd.CommandType = System.Data.CommandType.Text;
            int a = cmd.ExecuteNonQuery();
            if (a > 0)
            {
                MessageBox.Show("You Have Successfully Inserted");
                this.customer_InfoTableAdapter1.Fill(this.cD_GalleryDataSet7Cust_add.Customer_Info);
                Custid.Text = "";
                fname.Text = "";
                lname.Text = "";
                address.Text = "";
                contact.Text = "";
                email.Text = "";
                landmark.Text = "";
                deposite.Text = "";
            }
        }
    }

请编辑代码,这样我就可以知道。。。。。。。

如何避免在C#中使用windows窗体在SQL Server中插入重复记录

在运行查询以将数据插入客户数据表之前,请运行另一个查询以查看该记录是否已存在于表中。由于您没有提到这个表的mata数据,所以我正在编写一个示例查询,假设自己命名了一些属性。请尝试在插入查询之前运行此查询,如果此查询在结果集中返回一些值,则意味着该数据已存在于表中,因此请相应地告诉用户,否则,如果它返回NULL,则可以在表中插入数据,因为该数据尚不存在。

"select * from Customer_Info where cust_id = '" +Custid.Text.ToString()+"' OR contact = '" +contact.Text.ToString()+ "' OR email = '"+email.Text.ToString()+"'" ;

您可以使用UNIQUE约束来确保在不参与主键的特定列中不输入重复值。由于您的数据库中已经有表定义,您可以添加一个唯一的约束:

ALTER TABLE dbo.Customer_Info
ADD CONSTRAINT uccustomerinfo UNIQUE NONCLUSTERED (customer_id,contact_no, email);

点击此处查看演示

解决方案1: 如果您只想检查重复的CustomerID(一列)实际上您不需要为此编写任何逻辑,只需要将Custid列声明为IDENTITY即可解决问题。

IDENTITY列不需要从INSERT INTO语句中插入,它们将在默认情况下插入。

示例:如果您想以数字500开始Custid,并且每次插入都递增。

试试这个:

CREATE TABLE Customer
(
CustID int IDENTITY(500,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

在编写INSERT INTO语句时,可以跳过IDENTITY的值。

试试这个:

INSERT INTO Customer(LastName,FirstName,Address,City) 
              VALUES('xyz','abc','address','city');

解决方案2:您可以编写一个小函数来检测数据库中是否已经存在customerID。

试试这个:

bool CheckDuplicateCustomer(int custid,string contact,string email)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString = @"Data Source=HP'SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
    con.Open();
    if (con.State == System.Data.ConnectionState.Open)
    {
    SqlCommand cmd = new SqlCommand("select count(*) from Customer_Info where custid = @custid and contactno=@contactno and email=@email", con);
    cmd.Connection = con;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Parameters.AddWithValue("@custid",custid);
    cmd.Parameters.AddWithValue("@contactno",contact);
    cmd.Parameters.AddWithValue("@email",email);
    int CustomerCount = Convert.ToInt32(cmd.ExecuteScalar());
    }
    con.Close();
    if(CustomerCount > 0)
        return true;
    return false;
}

您可以调用上述功能来识别重复的客户

从您的代码中调用以下函数:

private void button1_Click(object sender, EventArgs e)
{
   int custid=Convert.ToInt32(CustID.Text);
   int contact=Contact.Text;
   int email=Email.Text;
   if(CheckDuplicateCustomer(custid,contact,email))
   {
         MessageBox.Show("Customer Already Exists with ID "+CustId.Text);
   }
   else
   {
     //your code to insert the customer into table
   } 
}