我有这个将数据插入数据库的代码。我想检查要插入的 ID 是否已经在数据库中。但如果它不在数据库中,则应将其插入。但是有一些错误,你能帮我解决一下吗?
public void Add()
{
sc.Open();
try
{
cmd = new SqlCommand("Select idnum from TableVotersInfo Where idnum=@idnum", sc);
cmd.Parameters.AddWithValue("@idnum", _idnum);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read() == true)
{
MessageBox.Show("ID number already exist!");
rd.Close();
}
else
{
cmd = new SqlCommand("INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult) VALUES (@ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum, 'Not Voted');", 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();
MessageBox.Show("Data Stored Successfully!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
编辑
我现在的错误是There is already an open DataReader associated with this command which must be closed first.
.
更新
public void Update()
{
sc.Open();
try
{
cmd = new SqlCommand("UPDATE TableVotersInfo SET Education=@ed, idnum=@idnum, FirstName=@firstname, MiddleName=@middlename, LastName=@lastname, SchoolYear=@schoolyear, ControlNum=@controlnum WHERE id=@id", 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);
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("Successfully Updated!");
FAddVoters._cleardata = cleardata;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}