在C#编程中,用Bcp批量复制数据,哪怕几百万的数据量,也可以轻松应对哦。
完整代码:
复制代码 代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace SqlBulkCopyDemo
{
public partial class Test : System.Web.UI.Page
{
public string SQLCONN = System.Configuration.ConfigurationManager.AppSettings["SQLCONN"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateXML();
//SqlBulkCopy();
}
}
#region //创建XML文件
public void CreateXML()
{
using (SqlConnection conn = new SqlConnection(SQLCONN))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from Student with(nolock)", conn);
DataSet ds = new DataSet();
da.Fill(ds);
ds.WriteXml(Server.MapPath(@"XMLSStudent.xml"));
}
}
#endregion www.jb200.com
#region //SqlBulkCopy批量导入数据
public void SqlBulkCopy()
{
DataSet ds = new DataSet();
DataTable sourceData = new DataTable();
ds.ReadXml(Server.MapPath(@"XMLSStudent.xml"));
sourceData = ds.Tables[0];
using (SqlConnection conn = new SqlConnection(SQLCONN))
{
conn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLCONN))
{
bulkCopy.ColumnMappings.Add("StudName", "StudName");
bulkCopy.ColumnMappings.Add("Sex", "Sex");
bulkCopy.ColumnMappings.Add("Age", "Age");
bulkCopy.ColumnMappings.Add("Birthday", "Birthday");
bulkCopy.ColumnMappings.Add("Tel", "Tel");
bulkCopy.ColumnMappings.Add("Email", "Email");
bulkCopy.ColumnMappings.Add("Address", "Address");
bulkCopy.ColumnMappings.Add("AddTime", "AddTime");
bulkCopy.DestinationTableName = "Student";
bulkCopy.WriteToServer(sourceData);
}
}
}
#endregion
#region //SqlBulkCopy批量导入数据(事务)
public void TransactionSqlBulkCopy()
{
DataSet ds = new DataSet();
DataTable sourceData = new DataTable();
ds.ReadXml(Server.MapPath(@"XMLSStudent.xml"));
sourceData = ds.Tables[0];
using (SqlConnection conn = new SqlConnection(SQLCONN))
{
conn.Open();
SqlTransaction Transaction=conn.BeginTransaction();//开启事务
using (SqlBulkCopy BulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default,Transaction))
{
try
{
BulkCopy.ColumnMappings.Add("StudName", "StudName");
BulkCopy.ColumnMappings.Add("Sex", "Sex");
BulkCopy.ColumnMappings.Add("Age", "Age");
BulkCopy.ColumnMappings.Add("Birthday", "Birthday");
BulkCopy.ColumnMappings.Add("Tel", "Tel");
BulkCopy.ColumnMappings.Add("Email", "Email");
BulkCopy.ColumnMappings.Add("Address", "Address");
BulkCopy.ColumnMappings.Add("AddTime", "AddTime");
BulkCopy.DestinationTableName = "Student";
BulkCopy.WriteToServer(sourceData);
BulkCopy.ColumnMappings.Clear();
Transaction.Commit();//事务提交
}
catch
{
Transaction.Rollback();//事务回滚
}
finally
{
Transaction.Dispose();//事务释放
}
}
}
}
#endregion
}
}