• 这样在一个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();
  • 相关阅读:
    Python 多线程学习(转)
    自己使用python webob,paste.deploy,wsgi总结
    Python中*args 和**kwargs的用法
    python 数字和字符串转换问题
    python socket编程
    深入解读Quartz的原理
    解决get方法传递URL参数中文乱码和解决tomcat下中文乱码问题
    Tomcat的Manager显示403 Access Denied
    mysql5.6 linux下安装笔记
    Quartz应用与集群原理分析
  • 原文地址:https://www.cnblogs.com/zxktxj/p/2737933.html
Copyright © 2020-2023  润新知