用于检查表列中存在的相同数据的代码

我遇到一个问题,在我的客户信息表中,客户ID,联系人号码和电子邮件地址对于两个或更多客户来说不应该相同。我还将custmomerid设置为主键。 Plz让我知道如何获取警告消息框,添加到数据库时已存在相同的数据……

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 = ""; } } } 

如果我理解正确,您需要防止在customerID,contactNo和Email上重复输入。 最直接的答案是将主键放在所有三列上。 这会在添加已存在的记录时抛出DuplicateRecordexception,您应该正确捕获它。

另一种方法是检入查询(使用执行标量):

“如果EXISTS(从customer_info中选择1,其中customerID = …并且contactNo = …和email = …)

BEGIN选择-1 RETURN END

插入Customer_Info值(’……….(您的查询)’

希望有所帮助