我使用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)
答案 0 :(得分:1)
有几个问题:
SqlAdapter
提供SqlCommandBuilder
。 Insert
/ Delete
命令SqlCommandBuilder
创建插入/删除命令后,您需要更改基础数据集,以便在Update
期间对表格进行任何更改。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
组合插入或删除行。