SqlDataAdapter.update()不更新数据库

时间:2015-04-07 04:22:48

标签: sql ado.net sqlcommandbuilder

我使用SqlDataAdapter在PostLikes表中搜索(PostId,UserId),如果找到该行,我使用SqlCommandBuilder.GetDeleteCommand()生成删除指令并删除基础行,如果是找不到,使用SqlCommandBuilder.GetInsertCommand()生成insert命令并使用SqlDataAdapter.Update()将行插入表中。但是这行没有插入到数据库中的表中。这就是我到目前为止所做的事情

SqlConnection con = new SqlConnection(connectionStrings);
                SqlDataAdapter sqlDataAdapter=new SqlDataAdapter("select * from PostLikes where PostId like "+postlike.PostId+" and UserId like "+postlike.UserId,con);
                DataSet ds = new DataSet();
                sqlDataAdapter.Fill(ds, "Result");
                con.Open();
                SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
                if(ds.Tables["Result"].Rows.Count==1)
                {
                    sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand(true);
                    msg = "Data is deleted";
                }
                else
                {
                    sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand(true);
                    msg = "Data is inserted";
                }
                sqlDataAdapter.Update(ds, "Result");

和表
PostLikes(LikeId,PostId,UserId)

1 个答案:

答案 0 :(得分:1)

有几个问题:

  • 您希望重复使用相同的命令来检测行是否存在,并为SqlAdapter提供SqlCommandBuilder
  • 您应该参数化初始选择查询以防止SqlInjection攻击(并且有一个小的性能优势)。 CommandBuilder将自动参数化Insert / Delete命令
  • 使用SqlCommandBuilder创建插入/删除命令后,您需要更改基础数据集,以便在Update期间对表格进行任何更改。
  • 请注意,许多Sql对象都是IDisposable,应该尽快处理 - using范围有用。

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

我假设了以下架构:

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

而且我以为你想要切换'使用postId, userid组合插入或删除行。