程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> sqlserver大批量數據寫入 sqlbulkcopy

sqlserver大批量數據寫入 sqlbulkcopy

編輯:關於SqlServer

 

//代碼備份

static void Main(string[] args)
{
string connectionString = "server=.;database=TianYa;uid=sa;pwd=sa;Max Pool Size = 512;";
DateTime time = DateTime.Now;
SqlBulkCopy sqlBC = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
sqlBC.DestinationTableName = "Users";
DataTable dt = new DataTable("Users");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("PassWord", typeof(string));
dt.Columns.Add("Email", typeof(string));
DirectoryInfo direct = new DirectoryInfo(@"D:\tianya");
string[] userInfo;
string readStr;
int totalNum = 0;
int partNum = 0;
int totalError = 0;
int partError = 0;
foreach (FileInfo NextFile in direct.GetFiles())
{
partNum = 0;
partError = 0;
Console.WriteLine("正在讀取文件:"+NextFile.FullName);
StreamReader sr = new StreamReader(NextFile.FullName, Encoding.Default);
while (sr.Peek() > -1)
{
totalNum++;
partNum++;
readStr = sr.ReadLine();
userInfo = readStr.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
try
{

if (userInfo.Length < 1) continue;
if (userInfo.Length < 2)
dt.Rows.Add(0, userInfo[0].Trim(), DBNull.Value, DBNull.Value);
else if (userInfo.Length < 3)
dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim(), DBNull.Value);
else
dt.Rows.Add(0, userInfo[0].Trim(), userInfo[1].Trim(), userInfo[2].Trim());
//foreach (string s in userInfo)
//{
// if (s.Length >= 50)
// MessageBox.Show(s.Length.ToString());
//}
}
catch (Exception e1)
{
Console.WriteLine(e1.Message);
totalError++;
partError++;
}
//if (flag % 100000 == 0)
//{
// try
// {
// sqlBC.WriteToServer(dt);
// }
// catch { }
// dt.Clear();
//}
}
sqlBC.WriteToServer(dt);
Console.WriteLine("文件" + NextFile.FullName + "轉換完成。本文件共有:" + partNum + " 條數據,其中失敗:" + partError + " 條");
dt.Clear();
sr.Close();
}
dt.Dispose();
sqlBC.Close();
Console.WriteLine("轉換完成。文件共有:" + totalNum + " 條數據,其中失敗:" + totalError + " 條");
Console.WriteLine("共耗時:" + (DateTime.Now - time).TotalSeconds.ToString() + " 秒");
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved