zoukankan      html  css  js  c++  java
  • 这样在一个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();
  • 相关阅读:
    一起来学SpringBoot(十七)优雅的参数校验
    使用JDBC创建出版社和书籍管理系统
    springMvc(初识+操作步骤)
    模拟Java-Sping,实现其IOC和AOP核心
    python多个装饰器的执行顺序
    JAVA——不简单的fianl关键字
    Java HTTP 组件库选型看这篇就够了
    这一次,我连 web.xml 都不要了,纯 Java 搭建 SSM 环境!
    13数据结构与算法分析之---链式栈
    12数据结构与算法分析之---顺序栈
  • 原文地址:https://www.cnblogs.com/zxktxj/p/2737933.html
Copyright © 2011-2022 走看看