zoukankan      html  css  js  c++  java
  • 数据批量写入

    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;
    }
    }

    }

  • 相关阅读:
    新版ubuntu中打开终端的方法和安装ssh 的方法
    HTML中利用404将老域名重定向到新域名
    KeelKit 1.0.3500.25185
    如何制作VSPackage的安装程序
    一副漫画:IE6滚回你老家去
    “表单控件”与“实体类”
    VS2005中得到 Web页面 或 窗体的 IDesignerHost
    一句SQL搞定分页
    CodeDom Assistant CodeDom的强大工具, 有些BUG修正了下,发到CodePlex,大家有需要的可以看看
    VS2005 出现 The OutputPath property is not set for this project. 错误的解决方法
  • 原文地址:https://www.cnblogs.com/rhythmK/p/2202016.html
Copyright © 2011-2022 走看看