黑马程序员技术交流社区
标题:
通过代码来对数据库进行Bulk Insert操作
[打印本页]
作者:
aisini
时间:
2014-8-13 14:25
标题:
通过代码来对数据库进行Bulk Insert操作
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace DemoApp
{
public class MyRecord
{
public int TestInt;
public string TestString;
public MyRecord()
{
}
public MyRecord(int myInt, string myString)
{
this.TestInt = myInt;
this.TestString = myString;
}
}
public class BulkUploadToSql
{
private List<MyRecord> internalStore;
protected string tableName;
protected DataTable dataTable = new DataTable();
protected int recordCount;
protected int commitBatchSize;
private BulkUploadToSql(
string tableName,
int commitBatchSize)
{
internalStore = new List<MyRecord>();
this.tableName = tableName;
dataTable = new DataTable(tableName);
recordCount = 0;
commitBatchSize = commitBatchSize;
// add columns to this data table
InitializeStructures();
}
private BulkUploadToSql() :
this("MyTableName", 1000) {}
private void InitializeStructures()
{
dataTable.Columns.Add("TI", typeof(Int32));
dataTable.Columns.Add("TS", typeof(string));
}
public static BulkUploadToSql Load(Stream dataSource)
{
// create a new object to return
BulkUploadToSql o = new BulkUploadToSql();
// replace the code below
// with your custom logic
for (int cnt = 0; cnt < 10000; cnt++)
{
MyRecord rec =
new MyRecord
(
cnt,
string.Format("string{0}", cnt)
);
o.internalStore.Add(rec);
}
return o;
}
private void WriteToDatabase()
{
// get your connection string
string connString = "";
// connect to SQL
using (SqlConnection connection =
new SqlConnection(connString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = this.tableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dataTable);
connection.Close();
}
// reset
dataTable.Clear();
recordCount = 0;
}
public void Flush()
{
// transfer data to the datatable
foreach (MyRecord rec in this.internalStore)
{
PopulateDataTable(rec);
if (recordCount >= this.commitBatchSize)
WriteToDatabase();
}
// write remaining records to the DB
if (recordCount > 0)
WriteToDatabase();
}
private void PopulateDataTable(MyRecord record)
{
// populate the values
// using your custom logic
DataRow row = this.dataTable.NewRow();
row[0] = record.TestInt;
row[1] = record.TestString;
// add it to the base for final addition to the DB
dataTable.Rows.Add(row);
recordCount++;
}
}
class Program
{
static void Main(string[] args)
{
using (Stream s =
new StreamReader(@"C:\TestData.txt"))
{
BulkUploadToSql myData =
BulkUploadToSql.Load(s);
myData.Flush();
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2