我的问题是,如果我更新除 之外的单个用户的所有数据idnum
,它总是显示 ID 号已经存在?我将如何保留身份证号码?
我的代码是:
public bool ExistsKey(string keyField, string table, string value, SqlConnection con)
{
try
{
if(con.State != ConnectionState.Open) con.Open();
using(SqlCommand com = new SqlCommand(
string.Format("IF EXISTS(SELECT * FROM {0} WHERE {1}={2}) SELECT 1 ELSE SELECT 0",
table, keyField, value), con))
{
var result = com.ExecuteScalar();
return result != null && (int)result == 1;
}
}
catch
{
return false;
}
finally
{
con.Close();
}
}
public void Update()
{
if (ExistsKey("idnum", "TableVotersInfo", _idnum.ToString(), sc))
{
MessageBox.Show("ID number already exist!");
FAddVoters._cleardata = "0";
FAddVoters._checkID = checkID;
}
else if (ExistsKey("idnum", "TableVotersInfo", _idnum.ToString(), sc))
{
}
else
{
if (sc.State != ConnectionState.Open) sc.Open();
try
{
using (cmd = new SqlCommand(@"UPDATE TableVotersInfo SET Education=@ed, idnum=@idnum, FirstName=@firstname, MiddleName=@middlename, LastName=@lastname, SchoolYear=@schoolyear, ControlNum=@controlnum WHERE id=@id
SELECT @ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum
WHERE @id NOT IN (SELECT idNum FROM TableVotersInfo);", sc))
{
cmd.Parameters.AddWithValue("@id", _id);
cmd.Parameters.AddWithValue("@ed", _ed);
cmd.Parameters.AddWithValue("@idnum", _idnum);
cmd.Parameters.AddWithValue("@firstname", _firstname);
cmd.Parameters.AddWithValue("@middlename", _middlename);
cmd.Parameters.AddWithValue("@lastname", _lastname);
cmd.Parameters.AddWithValue("@schoolyear", _schoolyear);
cmd.Parameters.AddWithValue("@controlnum", _controlnum);
cmd.ExecuteNonQuery();// <-- this is what you want
MessageBox.Show("Data Successfully Updated!");
FAddVoters._cleardata = cleardata;
FAddVoters._checkID = "0";
}
}
catch (SqlException ex)
{
if(ex.Number == 2627)//duplicated primary key
{
MessageBox.Show("ID number already exist!");
FAddVoters._cleardata = "0";
FAddVoters._checkID = checkID;
} else
{
MessageBox.Show("There was some error while attempting to update!\nTry again later.");
}
}
finally
{
sc.Close();
}
}
}
如果我编辑除 ID 号之外的特定行中的所有列,它仍然会告诉“ID 号已经存在!” 它不应该是。