SQL批量新增 和 C#客户端写法

2 篇文章 0 订阅

语句:Insert into Table Values (对应表字段1,对应表字段2,对应表字段3),(对应表字段1,对应表字段2,对应表字段3),(对应表字段1,对应表字段2,对应表字段3)·····

例:学生表:ID,学号,姓名,性别。 那么新增3条数据进去

Insert Into 学生表 Values(1001,张三,男),(1002,李四,女),(1003,王五,男)。

客户端代码如下:(注意SQL语句需要自己拼写,我的拼写方法如下,每500条新增一次,以防字符串长度过长)

string values = "";

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (values + "" == "")
                    {
                        values = string.Format("('{0}','{1}','{2}','{3}','{4}')", dt.Rows[i]["品种编号"], dt.Rows[i]["门市"],
                        (dt.Rows[i]["单据日期"] + "").Split(' ')[0], dt.Rows[i]["出库数量"], dt.Rows[i]["销售单据"]);
                    }
                    else
                    {
                        values = string.Format("{0},('{1}','{2}','{3}','{4}','{5}')", values, dt.Rows[i]["品种编号"], dt.Rows[i]["门市"],
                        (dt.Rows[i]["单据日期"] + "").Split(' ')[0], dt.Rows[i]["出库数量"], dt.Rows[i]["销售单据"]);
                    }
                    if ((i != 0 && i % 500 == 0 && values + "" != "") || (i == dt.Rows.Count - 1 && values + "" != ""))
                    {
                        string strSql = string.Format("INSERT INTO 二零一一市场库存出货 VALUES {0}", values);
                        GetXCJ_ERP2021Insert(strSql);
                        values = "";
                    }
                }

执行连接数据新增:注意:一定要用 CommandType.Text。

两个引用:

using System.Data;
using System.Data.SqlClient;

 private static int GetXCJ_ERP2021Insert(string strSql)
        {
            SqlConnection con = new SqlConnection("Data Source = 连接地址 ;Initial Catalog=数据库名称;User ID=sa;Password=密码;");//建立连接
            con.Open();//打开连接
            SqlCommand cmd = new SqlCommand(strSql, con);
            cmd.CommandType = CommandType.Text;
            int count = cmd.ExecuteNonQuery();
            con.Close();//关闭连接
            return count;
        }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值