SqlDataAdapter.update() not updating database

最后都变了- 提交于 2019-12-02 04:16:55

There are a couple of issues:

  • You are looking to reuse the same command to both detect whether the row exists, and to supply to the SqlAdapter for the SqlCommandBuilder.
  • You should parameterise the initial select query to protect against SqlInjection attacks (and there is a minor performance benefit). The CommandBuilder will automatically parameterize the Insert / Delete commands
  • After creating the Insert / Delete commands with the SqlCommandBuilder, you then need to change the underlying dataset in order for any changes to be made to the table during the Update.
  • Note that many of the Sql objects are IDisposable and should be disposed ASAP - using scopes help here.

.

var postId = 1;
var userId = 1;
string msg;
using (var con = new SqlConnection(@"data source=..."))
using (var selectCommand = new SqlCommand(
 "select LikeId, PostId, UserId from PostLikes WHERE PostId=@PostId AND UserId=@UserId", con))
using (var sqlDataAdapter = new SqlDataAdapter(selectCommand))
using (var ds = new DataSet())
{
    con.Open();
    selectCommand.Parameters.AddWithValue("@PostId", postId);
    selectCommand.Parameters.AddWithValue("@UserId", userId);
    sqlDataAdapter.Fill(ds, "Result");
    using (var sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter))
    {
        if (ds.Tables["Result"].Rows.Count == 1)
        {
            sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand(true);
            ds.Tables["Result"].Rows[0].Delete();
            msg = "Data will be deleted";
        }
        else
        {
            sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand(true);
            // Null because LikeId is Identity and will be auto inserted
            ds.Tables["Result"].Rows.Add(null, postId, userId);
            msg = "Data will be inserted";
        }
        sqlDataAdapter.Update(ds, "Result");
    }
}

I've assumed the following Schema:

CREATE TABLE PostLikes
(
    LikeId INT IDENTITY(1,1) PRIMARY KEY,
    PostId INT,
    UserId INT
)

And I've assumed you want to 'toggle' the insertion or deletion of a row with the postId, userid combination.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!