c# 加数据库锁,需要事务代码配合吗?
数据库中:快递=”申通“;
代码1:
using (con = SqlHelper.GetConnection())
{
string strsql=”SELECT * FROM aaa WITH (updlock) where state=0 and 快递='申通'“;
SqlDataAdapter da = new SqlDataAdapter(strsql, con);
SqlCommandBuilder SqlCommandBuilder = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "ta");
DataTable myTable = ds.Tables["ta"];
//---设定指定数据为锁定状态---------------------------------------------
foreach (DataRow myRow in myTable.Rows)
{
myRow["state"] = 1;
myRow["快递单号"]=1234567;
}
da.Update(ds, "ta");
ds.AcceptChanges();
}
代码2:
using (con = SqlHelper.GetConnection())
{
ds_read = SqlHelper.ExecuteReader(con, CommandType.Text, "SELECT * FROM aaa WITH (updlock) where state=0“;
if (ds_read.Read())
{
string strsql = "update aaa set 快递='顺丰' where state=0;
SqlHelper.ExecuteNonQuery(con, CommandType.Text, strsql);
}
}
1、目的是:当代码1设置state为1时,代码2无法无法更新快递字段为顺丰。但现实是冷酷的,由于经常同时执行,导致经常出现 快递字段是顺丰,快递单号字段却是 申通。
2、为了避免这个问题,查阅了大量的锁相关文章并使用了WITH (updlock)。并且从相关文章中了解到”锁需要包括在事务begin tran,commit tran“中。开始尝试使用begin tran,commit tran时,发现这个代码c#用不了。
问题1:WITH (updlock)的作用范围必须用 事务包起来吗?
问题2:上面代码中using{},是否能代替WITH (updlock)的作用范围?
问题3:上面用锁的这思路靠谱吗?
小白新手,麻烦大家多多帮助,都是这么过来的,只是有的人吸收知识快,而有的慢,我就是那慢的,总得熬啊,就100分了,大家帮忙看看?捞烦各位说的详细些,不然我这思维拗不过这弯。
至于,结帖率低,是因为,我真的不知道在哪找历史帖子,每次想结帖,都找不到,点自己的用户名,就是博客,收藏什么的。
不过不要担心,我想了个好办法,每次发完贴子,我都收藏起来,这样就能结帖了。