我在SQL Server数据库中有一个名为Contact
的表。唯一的主键是contactID
。以下是用于创建此表的脚本部分:
CREATE TABLE [dbo].[contact]
(
[contactID] [int] IDENTITY(1,1) NOT NULL,
[lName] [varchar](45) NOT NULL,
[fName] [varchar](45) NOT NULL,
[dob] [date] NOT NULL,
[mailingAddressStreet] [varchar](100) NOT NULL,
[mailingAddressCity] [varchar](100) NOT NULL,
[mailingAddressState] [char](2) NOT NULL,
[mailingAddressZip] [char](5) NOT NULL,
[phoneNumber] [varchar](20) NOT NULL,
[gender] [char](1) NULL,
[SSN] [char](9) NOT NULL,
[userType] [int] NOT NULL,
PRIMARY KEY CLUSTERED ([contactID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
以下是我在C#中用于执行更新的方法:
public static bool UpdatePatient(int contactID, string lastName, string firstName, DateTime DOB, string street, string city, string state,
string ZIP, string phone, string gender, string SSN)
{
bool isUpdated = false;
string updateStmt = "UPDATE contact SET lName = @lastName, fName = @firstName, dob = @DOB, mailingAddressStreet = @street, " +
"mailingAddressCity = @city, mailingAddressState = @state, mailingAddressZip = @ZIP, phoneNumber = @phone, gender = @gender, ssn = @SSN " +
"WHERE contactID = @contactID";
try
{
using (SqlConnection connect = DBConnection.GetConnection())
{
connect.Open();
using (SqlCommand cmd = new SqlCommand(updateStmt, connect))
{
cmd.Parameters.AddWithValue("@contactID", contactID);
cmd.Parameters.AddWithValue("@lastName", lastName);
cmd.Parameters.AddWithValue("@firstName", firstName);
cmd.Parameters.AddWithValue("@DOB", DOB);
cmd.Parameters.AddWithValue("@street", street);
cmd.Parameters.AddWithValue("@city", city);
cmd.Parameters.AddWithValue("@state", state);
cmd.Parameters.AddWithValue("@ZIP", ZIP);
cmd.Parameters.AddWithValue("@phone", phone);
cmd.Parameters.AddWithValue("@gender", gender);
cmd.Parameters.AddWithValue("@SSN", SSN);
isUpdated = (cmd.ExecuteNonQuery() > 0);
}
connect.Close();
}
return isUpdated;
}
catch (SqlException sqlex)
{
throw sqlex;
}
catch (Exception ex)
{
throw ex;
}
}
我知道视图正在传递正确的参数,所以这不是问题。但是,当我运行我的应用程序并尝试更新某人的联系信息时,我收到如下错误:
违反UNIQUE KEY约束UQ_contact_CA1E8E3C4CEC5645。无法在对象'dbo.contact'中插入重复键。重复键值为(333222112)。
该号码“333222112”是SSN(当然,完全用于测试目的)。虽然作为测试运行更新,但实际上我保持SSN不变。但是,包含SSN的功能非常重要,以防需要在输入错误后进行纠正。更新表单已预先填充了所有联系人信息,用户可以在单击要更新的按钮之前进行任何他们想要的更改,这会调用此方法。