语句: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;
}