SqlBulkCopy批量插入数据
private void uiButton1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("CreateBy", typeof(System.Int64)); dt.Columns.Add("CreateTime", typeof(System.DateTime)); dt.Columns.Add("UpdateBy", typeof(System.Int64)); dt.Columns.Add("UpdateTime", typeof(System.DateTime)); dt.Columns.Add("IsDelete", typeof(System.Int32)); dt.Columns.Add("platform", typeof(System.Int32)); dt.Columns.Add("WebSiteId", typeof(System.Int64)); dt.Columns.Add("GoodsId", typeof(System.String)); dt.Columns.Add("Same_platform", typeof(System.Int32)); dt.Columns.Add("Same_GoodsId", typeof(System.String)); dt.Columns.Add("Same_Similarity", typeof(System.Double)); dt.Columns.Add("Same_GoodsName", typeof(System.String)); dt.Columns.Add("Same_GoodsUrl", typeof(System.String)); dt.Columns.Add("Same_ImageUrl", typeof(System.String)); dt.Columns.Add("Same_Price", typeof(System.Double)); dt.Columns.Add("Same_Sold", typeof(System.Int32)); var bll = new Database.BLL.Local.Gd_FindSameDbBll(); List<Database.Model.Local.Gd_FindSame> list = bll.QueryAll(); List<Gd_FindSame_Detail> list1 = new List<Gd_FindSame_Detail>(); for (int i = 0; i < list.Count; i++) { var same = list[i]; //var count = Database.Instance.FindSame_DetailDbBll.Count($"GoodsId='{ same.GoodsId}' and Same_GoodsId='{same.Same_GoodsId}'"); //if (count > 0) // continue; DataRow dr = dt.NewRow(); dr["CreateBy"] = 4; dr["CreateTime"] = DateTime.Now; dr["UpdateBy"] = 4; dr["UpdateTime"] = DateTime.Now; dr["IsDelete"] = 0; dr["platform"] = same.platform; dr["WebSiteId"] = same.WebSiteId; dr["GoodsId"] = same.GoodsId; dr["Same_platform"] = same.Same_platform; dr["Same_GoodsId"] = same.Same_GoodsId; dr["Same_Similarity"] = same.Same_Similarity; dr["Same_GoodsName"] = same.Same_GoodsName; dr["Same_GoodsUrl"] = same.Same_GoodsUrl; dr["Same_ImageUrl"] = same.Same_ImageUrl; dr["Same_Price"] = same.Same_Price; dr["Same_Sold"] = same.Same_Sold; dt.Rows.Add(dr); } SqlBulkCopyByDatatable(SqlHelper.dbConn, "Gd_FindSame_Detail", dt); } /// <summary> /// /// </summary> /// <param name="connectionString">目标连接字符</param> /// <param name="TableName">目标表</param> /// <param name="dt">源数据</param> private void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt) { using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) { try { sqlbulkcopy.BulkCopyTimeout = 180; sqlbulkcopy.DestinationTableName = TableName; for (int i = 0; i < dt.Columns.Count; i++) { sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); } sqlbulkcopy.WriteToServer(dt); } catch (System.Exception ex) { throw ex; } } } }