代码如下,请给出具体修改代码
public void AddCategory(string nCategoryName, int nImgId, int nBelongToId, int nShopId, int nSortId)
{
int CategoryId = 0;
string cmdText = "Select top 1 CategoryId from ProductCategory where CategoryName='' ROWLOCK";
SqlConnection conn = new SqlConnection(Connection.ConnString);
SqlCommand cmd = new SqlCommand(cmdText, conn);
conn.Open();
SqlTransaction tr = conn.BeginTransaction();
cmd.Transaction = tr;
try
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
CategoryId = Int32.Parse(dr["CategoryId"].ToString());
}
dr.Close();
if (CategoryId == 0)
{
cmd.CommandText = "INSERT ProductCategory(CategoryName,ImgId,BelongToId,ShopId,SortId) VALUES('" + nCategoryName + "','" + nImgId + "','" + nBelongToId + "','" + nShopId + "','" + nSortId + "')";
cmd.ExecuteNonQuery();
}
else
{
cmd.CommandText = "Update ProductCategory Set CategoryName='" + nCategoryName + "',ImgId='" + nImgId + "',BelongToId='" + nBelongToId + "',SortId='" + nSortId + "',ShopId='" + nShopId + "' Where CategoryId=" + CategoryId;
cmd.ExecuteNonQuery();
}
tr.Commit();
}
catch
{
tr.Rollback();
}
finally { conn.Close(); }
}
你这样在并发多的时候很可能造成冲突的,直接用:
cmd.CommandText = @"Update ProductCategory set xxx where xxx
if @@ROWCOUNT = 0
insert into ProductCategory xxx";
这样在一个sql里完成更新和插入,只用一次数据库连接,效率提高了,并发可能也减小了
是sql,SqlServer支持同时执行多个sql的
后面直接cmd.ExecuteNonQuery();