C#大数据导入-SqlBulkCopy

方法1:DataTable方式

        /// 
        /// 批量新增数据(限Excel使用)
        /// 
        /// DataTable(其中的列名要与数据库表列名一致)
        public int BatchAdd(DataTable dt)
        {
            int rs = 1;
            SqlConnection sqlConn =
                new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
            try
            {
                sqlConn.Open();
                SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(sqlConn);
                sqlbulkcopy.DestinationTableName = "PhoneToQRCode";//数据库中的表名
                sqlbulkcopy.WriteToServer(dt);
            }
            catch (Exception ex)
            {
                rs = 0;
            }
            finally
            {
                sqlConn.Close();
            }
            return rs;
        }

方法2:使用List方式

        /// 
        /// 批量插入
        /// 
        /// 
        /// 源数据
        internal static void BulkCopy(IDbConnection conn, IEnumerable list)
        {
            var dt = list.ToDataTable();

            using (conn)
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();

                using (var sqlbulkcopy = new SqlBulkCopy((SqlConnection)conn))
                {
                    sqlbulkcopy.DestinationTableName = dt.TableName;
                    for (var i = 0; i < dt.Columns.Count; i++)
                    {
                        sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
                    }
                    sqlbulkcopy.WriteToServer(dt);
                }
            }
        }

        /// 
        /// List转DataTable
        /// 
        /// 
        /// 集合
        /// 
        public static DataTable ToDataTable(this IEnumerable list)
        {
            var type = typeof(T);

            var properties = type.GetProperties().ToList();

            var newDt = new DataTable(type.Name);

            properties.ForEach(propertie =>
            {
                Type columnType;
                if (propertie.PropertyType.IsGenericType && propertie.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    columnType = propertie.PropertyType.GetGenericArguments()[0];
                }
                else
                {
                    columnType = propertie.PropertyType;
                }

                newDt.Columns.Add(propertie.Name, columnType);
            });

            foreach (var item in list)
            {
                var newRow = newDt.NewRow();

                properties.ForEach(propertie =>
                {
                    newRow[propertie.Name] = propertie.GetValue(item, null) ?? DBNull.Value;
                });

                newDt.Rows.Add(newRow);
            }

            return newDt;
        }

你可能感兴趣的:(C#大数据导入-SqlBulkCopy)