繁体   English   中英

数据库更新问题

[英]Issues With Database Update

我尝试使用此代码更新数据库。 出现此消息,表明数据库已更新,但数据库中的记录未更改。 这是我正在使用的代码。 请问我有什么错误吗?

    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;
    }
   sqlcmd.ExecuteScalar(); //Excute scalar give only Single Cell it Is not meaningful to use to update

 sqlcmd.ExecuteNonQuery();// Use to Inser/Update Statement...

ExecuteScalar 返回一些数据,该数据是第一列的第一行。 由于您的命令是UPDATE ,因此在这种情况下没有必要使用ExecuteScalar ,因为命令上没有返回任何数据。

您需要在第二个sqlcmmd使用ExecuteNonQuery ,因为您的命令是UPDATE语句,并且此方法仅执行您的查询。

也可以使用using语句来处理SqlConnectionSqlCommand

并且不要使用AddWithValue方法。 可能会产生意外的结果。 使用SqlParameterCollection.Add()或它的重载代替。

阅读: 我们可以停止使用AddWithValue()吗?

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM