zoukankan      html  css  js  c++  java
  • Sql批量插入方法

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.SqlClient;
    using System.Linq;

    namespace TY.Tools
    {

            /// <summary>  
            /// 批量插入  
            /// </summary>  
            /// <typeparam name="T">泛型集合的类型</typeparam>  
            /// <param name="conn">连接对象</param>  
            /// <param name="tableName">将泛型集合插入到本地数据库表的表名</param>  
            /// <param name="list">要插入大泛型集合</param>  
            public static void BulkInsert<T>(SqlConnection conn, string tableName, IList<T> list)
            {
                using (var bulkCopy = new SqlBulkCopy(conn))
                {
                    bulkCopy.BatchSize = list.Count;
                    bulkCopy.DestinationTableName = tableName;
    
                    var table = new DataTable();
                    var props = TypeDescriptor.GetProperties(typeof(T))
    
                        .Cast<PropertyDescriptor>()
                        .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                        .ToArray();
    
                    foreach (var propertyInfo in props)
                    {
                        bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                        table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
                    }
    
                    var values = new object[props.Length];
                    foreach (var item in list)
                    {
                        for (var i = 0; i < values.Length; i++)
                        {
                            values[i] = props[i].GetValue(item);
                        }
    
                        table.Rows.Add(values);
                    }
    
                    bulkCopy.WriteToServer(table);
                }
            }
    }
  • 相关阅读:
    LSMW TIPS
    Schedule agreement and Delfor
    Running VL10 in the background 13 Oct
    analyse idoc by creation date
    New Journey Prepare
    EDI error
    CBSN NEWS
    Listen and Write 18th Feb 2019
    Microsoft iSCSI Software Target 快照管理
    通过 Microsoft iSCSI Software Target 提供存储服务
  • 原文地址:https://www.cnblogs.com/oumi/p/10480285.html
Copyright © 2011-2022 走看看