生活随笔
收集整理的這篇文章主要介紹了
这样在一个sql里完成更新和插入,只用一次数据库连接,效率提高了
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼如下,請給出具體修改代碼 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();
轉載于:https://www.cnblogs.com/zxktxj/archive/2012/10/24/2737933.html
總結
以上是生活随笔 為你收集整理的这样在一个sql里完成更新和插入,只用一次数据库连接,效率提高了 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。