数据批量写入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;

namespace SQLBulkInsertTest
{
/// <summary>
/// 测试数据批量插入 By RhythmK
/// </summary>
/* -------------数据库表脚本---------------
CREATE TABLE [dbo].[Man](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Age] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,

CONSTRAINT [PK_Man] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

*/
class Program
{
private const string constr = "Data Source=H-WK2011;Initial Catalog=Test;Integrated Security=True";
static void Main(string[] args)
{
AddList();
}
public static void AddList()
{
List<Man> list = new List<Man>();
list.Add(new Man { Age=15, Name="Rhythmk" });
list.Add(new Man { Age=18, Name="Rhythmk1"});
DataTable dt = list.ToDataTable();

using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(constr))
{
// 对应插入数据表名
sqlBulkCopy.DestinationTableName = "Man";
sqlBulkCopy.WriteToServer(dt);
}

Console.WriteLine("-数据写入成功-");
Console.ReadKey();

}
}
public class Man
{
public int Age
{
get;
set;
}
public string Name
{
get;
set;
}
}

public static class Help
{
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable(this IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}

for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
}

}

原文地址:https://www.cnblogs.com/rhythmK/p/2202016.html