违反主键constarint sql server [英] Violation of Primary key constarint sql server
问题描述
我有一个用C#编写的程序。我的后台有一个INSERT SQL。但是我已将单个字段设置为主键,因此如果您输入相同的详细信息,则会引发异常。我想创建一个消息框,向用户显示
详细信息已存在。我该怎么办?以下是代码:
I have a program written in C#. I have an INSERT SQL in its background. However i have set a single field as a primary key and as a result if u enter the same details, it throws an exception. I want to create a message box that displays to the user that the detail already exists. How do i go about. Below is the code:
private void btnsave_Click(object sender,RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand(" Insert into Passengers values(@ID_Number,@ Name,@ Frrom,@ To,@ Phone,@ Time_Out,@ Date,@ Price)",con);
cmd.Parameters.AddWithValue(" ID_Number",txtid.Text);
cmd.Parameters.AddWithValue(" Name",txtname.Text);
cmd.Parameters.AddWithValue(" From",txtfrom.Text);
cmd.Parameters.AddWithValue(" To",txt_to.Text);
cmd.Parameters.AddWithValue(" Phone",txtphone.Text);
cmd.Parameters.AddWithValue(" Time_Out",txt_time.Text);
cmd.Parameters.AddWithValue(" Date",txtdate.Text);
cmd.Parameters.AddWithValue(" Price",txtprice.Text);
cmd.ExecuteNonQuery();
$
txtid.Text ="" ;;
txtname.Text ="" ;;
txtfrom.Text ="" ;;
txt_to.Text ="" ;;
txtphone.Text ="" ;;
txt_time.Text ="" ;;
txtdate.Text ="" ;;
txtprice.Text ="";
private void btnsave_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into Passengers values (@ID_Number, @Name, @From, @To, @Phone, @Time_Out, @Date, @Price)", con);
cmd.Parameters.AddWithValue("ID_Number", txtid.Text);
cmd.Parameters.AddWithValue("Name", txtname.Text);
cmd.Parameters.AddWithValue("From", txtfrom.Text);
cmd.Parameters.AddWithValue("To", txt_to.Text);
cmd.Parameters.AddWithValue("Phone", txtphone.Text);
cmd.Parameters.AddWithValue("Time_Out", txt_time.Text);
cmd.Parameters.AddWithValue("Date", txtdate.Text);
cmd.Parameters.AddWithValue("Price", txtprice.Text);
cmd.ExecuteNonQuery();
txtid.Text = "";
txtname.Text = "";
txtfrom.Text = "";
txt_to.Text = "";
txtphone.Text = "";
txt_time.Text = "";
txtdate.Text = "";
txtprice.Text = "";
}
}
}
}
}
}
推荐答案
我有一个用C#编写的程序。我的后台有一个INSERT SQL。但是我已将单个字段设置为主键,因此如果您输入相同的详细信息,则会引发异常。我想创建一个消息框,向用户显示详细信息已存在的
。我该怎么办?以下是代码:
您获取密钥信息并阅读记录。
You take the key information and you do a read for the record.
如果记录存在,然后你停止进一步处理,发出一条消息,表示该表中的记录已存在该键,并保留该方法,否则,如果表中不存在带密钥的记录,则继续记录插入密钥。
If the record exist, then you stop further processing, put out a message that the key already exist for a record in the table and leave the method, else, if record with key doesn't exist in the table, then you proceed with the record insert with key.
这篇关于违反主键constarint sql server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!