Reputation: 31
I try to update my database using this code. The message comes up that the database has neen updated but the records do not change in the database. Here are the codes I am using. Please is there any error I am committing?
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;
}
Upvotes: 1
Views: 59
Reputation: 98868
ExecuteScalar
returns some data which is the first row of the first column. Since your command is UPDATE
, there is no point to use ExecuteScalar
in such a case because no data returned on your command.
You need to use ExecuteNonQuery
in your second sqlcmmd
because your command is UPDATE
statement and this method just executes your query.
Also use using
statement to dispose your SqlConnection
and SqlCommand
.
And don't use AddWithValue
method. It may generate unexpected results. Use SqlParameterCollection.Add()
or it's overloads instead.
Read: 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();
}
}
Upvotes: 0
Reputation: 2379
sqlcmd.ExecuteScalar(); //Excute scalar give only Single Cell it Is not meaningful to use to update
sqlcmd.ExecuteNonQuery();// Use to Inser/Update Statement...
Upvotes: 1