我有問題,雖然我檢查數據庫中不存在主鍵。附加信息:不能在對象中插入重複鍵
附加信息:違反PRIMARY KEY約束條件 'PK_Yeucaukhachhang'。不能在對象 'dbo.Yeucaukhachhang'中插入重複密鑰。重複的鍵值是(MH01123123)。
using (SqlConnection sqlCon = new SqlConnection(sqlCnt))
{
for (int i = 0; i < metroGrid2.Rows.Count; i++)
{
SqlCommand cmd = new SqlCommand("INSERT INTO
Yeucaukhachhang(MaKH,MaHang,TenHang,DonViTinh,Dongia,
SoLuong,Duyet) values('"+ makh.Text+"','"+
metroGrid2.Rows[i].Cells["mahang"].Value +
"','"+metroGrid2.Rows[i].Cells["tenhang"].Value+"', '"+
metroGrid2.Rows[i].Cells["donvitinh"].Value+"', '"+
metroGrid2.Rows[i].Cells["dongia"].Value+"', '"+
metroGrid2.Rows[i].Cells["soluong"].Value+"', 'N')", sqlCon);
SqlCommand cmd1 = new SqlCommand("INSERT INTO DanhMucKhachHang(MaKhachHang,TenKhachHang,DiaChiKhachHang,SDTKhachHang,CMD,masothue,thanhtoan,nganhang,taikhoannganhang,ngaythang,MaHang,TenHang,DonViTinh,Dongia,SoLuong,Duyet) VALUES(@MaKhachHang,@TenKhachHang,@DiaChiKhachHang,@SDTKhachHang,@CMD,@masothue,@thanhtoan,@nganhang,@taikhoannganhang,@ngaythang)", sqlCon);
cmd1.Parameters.AddWithValue("@MaKhachHang", makh.Text);
cmd1.Parameters.AddWithValue("@TenKhachHang", namekh.Text);
cmd1.Parameters.AddWithValue("@DiaChiKhachHang", address.Text);
cmd1.Parameters.AddWithValue("@SDTKhachHang", phone.Text);
cmd1.Parameters.AddWithValue("@CMD", idkh.Text);
cmd1.Parameters.AddWithValue("@masothue", idthue.Text);
cmd1.Parameters.AddWithValue("@thanhtoan", deliver.Text);
cmd1.Parameters.AddWithValue("@nganhang", bank.Text);
cmd1.Parameters.AddWithValue("@taikhoannganhang", idacc.Text);
cmd1.Parameters.AddWithValue("@ngaythang", this.datekh.Value);
sqlCon.Open();
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("Thêm thành công, đa chuyển qua xác nhận yêu cầu");
LTQL.Home.Home cort = new LTQL.Home.Home();
cort.Show();
this.Hide();
}
1.檢查數據庫名稱是否正確。 2.編寫sql刪除makh = MH01123123並重試。 –
爲什麼使用'cmd1'的參數化查詢,而不是'cmd'? –
請發表您的表結構Yeucaukhachhang – tharif