我试着用这段代码更新我的数据库。出现的消息是数据库没有更新,但数据库中的记录没有更改。这是我正在使用的代码。请问我犯了什么错误吗?
private void titheEditBtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=EPRAISE-PC;Initial Catalog=Cmanager;Integrated Security=True");
SqlCommand sqlcmd = new SqlCommand("Select Count(MemberID) from Tithe where MemberID = @MemberID", con);
sqlcmd.Parameters.AddWithValue("@MemberID", titheMemID.Text);
con.Open();
int UserExist = (int)sqlcmd.ExecuteScalar();
if (UserExist > 0)
{
SqlCommand sqlcmmd = new SqlCommand("Update Tithe SET Amount = @titheAmount, Date = @titheDate where MemberID = @MemberID AND Date = @titheDate");
sqlcmmd.Parameters.AddWithValue("@MemberID", titheMemID.Text);
sqlcmmd.Parameters.AddWithValue("@titheAmount", titheAmount.Text);
sqlcmmd.Parameters.AddWithValue("@titheDate", titheDateTime.Text);
sqlcmd.ExecuteScalar();
titheEditMsg.Visible = true;
}
else
{
MessageBox.Show("No Such Record Exists");
}
con.Close();
///titheEditMsg.Visible = false;
}
最佳答案
ExecuteScalar
返回第一列的第一行数据。由于您的命令是UPDATE
,因此在这种情况下没有必要使用ExecuteScalar
,因为您的命令上没有返回任何数据。
您需要在第二个ExecuteNonQuery
中使用sqlcmmd
,因为您的命令是UPDATE
语句,而此方法只执行您的查询。
也可以使用using
statement来处理您的SqlConnection
和SqlCommand
。
不要使用AddWithValue
方法。它可能会产生意想不到的结果。使用SqlParameterCollection.Add()
或者它是重载。
阅读:Can we stop using AddWithValue()
already?
using(SqlConnection con = new SqlConnection(@"Data Source=EPRAISE-PC;Initial Catalog=Cmanager;Integrated Security=True"))
{
....
....
using(SqlCommand sqlcmmd = con.CreateCommand())
{
sqlcmmd.CommandText = "Update Tithe SET Amount = @titheAmount, Date = @titheDate where MemberID = @MemberID AND Date = @titheDate";
sqlcmmd.Parameters.Add("@MemberID").Value = titheMemID.Text;
sqlcmmd.Parameters.Add("@titheAmount").Value = titheAmount.Text;
sqlcmmd.Parameters.Add("@titheDate").Value = titheDateTime.Text;
con.Open();
sqlcmmd.ExecuteNonQuery();
}
}