#region 将Xml中的数据读到Dataset中,然后用SqlBulkCopy类把数据copy到目的表中
using (XmlTextReader xmlReader = new XmlTextReader(sourcePath))
{
DataSet ds = new DataSet();
ds.ReadXml(XmlReader.Create(sourcePath));//把数据读到DataSet这个过程有点慢,取决于XML文件大小
using (SqlBulkCopy bcp = new SqlBulkCopy(targetDBCon))
{
bcp.BatchSize = ds.Tables[0].Rows.Count;
bcp.DestinationTableName = targetTableName;
#region 源表和目的表列匹配,只导入匹配列对应的数据;如果XML中的节点能和目的表中的栏位一一对应,这段程序可不要。
StringBuilder sbSQL = new StringBuilder();
sbSQL.AppendFormat("select top 1 * from {0}", targetTableName);
DbHelperSQL dbHelper = new DbHelperSQL();//自定义数据库操作类
DataTable dt = dbHelper.GetDataTable(targetDBCon, sbSQL.ToString());
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
if (dt.Columns[i].ColumnName == ds.Tables[0].Columns[j].ColumnName)
bcp.ColumnMappings.Add(ds.Tables[0].Columns[j].ColumnName, dt.Columns[i].ColumnName);
}
}
#endregion
bcp.WriteToServer(ds.Tables[0]);
}
}
#endregion