您的位置:首页 > 数据库

这样在一个sql里完成更新和插入,只用一次数据库连接,效率提高了

2012-10-24 22:59 866 查看
代码如下,请给出具体修改代码
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐