我继承了一个项目,我遇到了一个SQL错误,我不知道如何解决。
在一个电子商务网站上,代码正在将订单运输信息插入到另一个数据库表中。
下面是将信息插入到表中的代码。
string sql = "INSERT INTO AC_Shipping_Addresses
(pk_OrderID, FullName, Company, Address1, Address2, City, Province, PostalCode, CountryCode, Phone, Email, ShipMethod, Charge_Freight, Charge_Subtotal)
VALUES (" + _Order.OrderNumber;
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToCompany == "")
sql += ", '" + _Order.Shipments[0].ShipToFullName.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].ShipToCompany.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Address1.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Address2.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.City.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Province.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.PostalCode.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Country.Name.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].Address.Phone.Replace("'", "''") + "'";
if (_Order.Shipments[0].ShipToEmail == "")
sql += ",'" + _Order.BillToEmail.Replace("'", "''") + "'";
sql += ",'" + _Order.Shipments[0].ShipToEmail.Replace("'", "''") + "'";
sql += ", '" + _Order.Shipments[0].ShipMethod.Name.Replace("'", "''") + "'";
sql += ", " + shippingAmount;
sql += ", " + _Order.ProductSubtotal.ToString() + ")";
bll.dbUpdate(sql);
它工作正常,但它也输出了以下SQL错误。
违反了PRIMARY KEY约束 "PK_AC_Shipping_Addresses"。不能插入
不能在对象'dbo.AC_Shipping_Addresses'中插入重复的键。重复键的值
是(165863)。
通过阅读类似的问题,我似乎应该在语句中声明ID。
这是正确的吗?我将如何调整代码来解决这个问题?