我正在 c# winform 中更新数据库中的数据。当我更新时,如果我的数据中有相同的 IDnum,我不希望它更新。我的 bool 方法有问题。
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 (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();
}
}
}
我在这里做错了什么?问题出在我的bool
.
一些错误,例如
var result = com.ExecuteScalar();
= '无效的初始化器成员声明器。'
我的桌子
(来源:akamaihd.net)