您的位置:首页 > 数据库 > SQL

SqlBulkCopy 快速插入数据库

2012-01-05 18:16 387 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Data.SqlClient;

namespace sqlBulkCopy
{
class Program
{
static void Main(string[] args)
{
List<string> listFile = new List<string>();
StreamReader objReaderTemp = new StreamReader("c:\\766_happy.txt");
string fileLine = "";
while (fileLine != null)
{
fileLine = objReaderTemp.ReadLine();
if (fileLine != null)
{
listFile.Add(fileLine);
//Console.WriteLine(fileLine);
}
}

string constr = "Data Source=.;Initial Catalog=db_userpsw;Integrated Security=True";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("info", typeof(string));

int count = 0;
int countfile = 0;

foreach (string strFileTemp in listFile)
{
countfile++;

StreamReader objReader = new StreamReader(strFileTemp, System.Text.Encoding.Default);

string sLine = "";

while (sLine != null)
{

sLine = objReader.ReadLine();

if (sLine != null&&sLine.Length<150)
{

DataRow dr = dt.NewRow();
dr["info"] = sLine;
dt.Rows.Add(dr);
count++;
if (count % 10000 == 0)
{
Console.WriteLine(count);

using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
sqlBC.BatchSize = 10000;
sqlBC.DestinationTableName = "dbo.t766_happy";
sqlBC.ColumnMappings.Add("info", "info");
sqlBC.WriteToServer(dt);
}
dt.Clear();
}

}//end if
}//end while
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
sqlBC.BatchSize = 1000;
sqlBC.DestinationTableName = "dbo.t766_happy";
sqlBC.ColumnMappings.Add("info", "info");
sqlBC.WriteToServer(dt);
Console.WriteLine("last data :"+countfile);
}
dt.Clear();
}
conn.Dispose();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: