我遇到了一个问题,在我的客户信息表中有客户ID,请联系no&两个或更多客户的电子邮件地址不应该相同。我还将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 = "";
}
}
}
答案 0 :(得分:2)
如果我理解正确,您需要防止在customerID,contactNo和Email上重复输入。最直接的答案是将主键放在所有三列上。这会在添加已经存在的记录时抛出DuplicateRecord异常,你应该正确捕获它。
另一种方法是检入查询(使用执行标量):
" IF EXISTS(从customer_info中选择1,其中customerID = ...和 contactNo = ...和email = ...)
BEGIN选择-1返回结束
插入Customer_Info值(' ..........(您的查询)"
希望有所帮助