C#批量将数据插入SQLServer数据库

时间:2021-02-22 23:09:53

Database db = CreateDatabase();
                var varConnnection = db.CreateConnection();     //获取连接字符串对象
                SqlBulkCopy sqlBulkcopy = new SqlBulkCopy(varConnnection.ConnectionString);
                sqlBulkcopy.DestinationTableName = "T_ACl_User_Function";   //数据库表名字
                sqlBulkcopy.BatchSize = dt.Rows.Count;
                try
                {
                    varConnnection.Open();
                    if (dt != null && dt.Rows.Count != 0)
                    {
                        sqlBulkcopy.WriteToServer(dt);  //批量插入到数据库中
                        init = 1;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    varConnnection.Close();
                    if (sqlBulkcopy != null)
                        sqlBulkcopy.Close();
                }
                return init;