將幾百萬條數據導入到數據庫中,怎麼樣高效率的導入?sql
下面我就介紹一個高效率的方法:數據庫
一、將數據庫文件(DB.csv)導入到DataTable中:測試
/// <summary>pwa
/// 將CSV文件的數據讀取到DataTable中orm
/// </summary>utf-8
/// <param name="fileName">CSV文件路徑</param>cmd
/// <returns>返回讀取了CSV數據的DataTable</returns>string
public static DataTable OpenCSV(string filePath)it
{io
Encoding encoding = Encoding.GetEncoding("utf-8"); //Encoding.ASCII;//
DataTable dt = new DataTable();
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//StreamReader sr = new StreamReader(fs, Encoding.UTF8);
StreamReader sr = new StreamReader(fs, encoding);
//string fileContent = sr.ReadToEnd();
//encoding = sr.CurrentEncoding;
//記錄每次讀取的一行記錄
string strLine = "";
//記錄每行記錄中的各字段內容
string[] aryLine = null;
string[] tableHead = null;
//標示列數
int columnCount = 0;
//標示是不是讀取的第一行
bool IsFirst = true;
//逐行讀取CSV中的數據
while ((strLine = sr.ReadLine()) != null)
{
//strLine = Common.ConvertStringUTF8(strLine, encoding);
//strLine = Common.ConvertStringUTF8(strLine);
if (IsFirst == true)
{
tableHead = strLine.Split(',');
IsFirst = false;
columnCount = tableHead.Length;
//建立列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(tableHead[i]);
dt.Columns.Add(dc);
}
}
else
{
if (!String.IsNullOrEmpty(strLine))
{
aryLine = strLine.Split(',');
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j];
}
dt.Rows.Add(dr);
}
}
}
if (aryLine != null && aryLine.Length > 0)
{
dt.DefaultView.Sort = tableHead[0] + " " + "asc";
}
sr.Close();
fs.Close();
return dt;
}
}
二、將數據庫保存到數據庫:
public static void TableValuedToDB(DataTable dt)
{
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
const string TSqlStatement =
"insert into table (col1,col2)" +
" SELECT nc.col1,nc.col2" +
" FROM @NewBulkTestTvp AS nc";
SqlCommand cmd = new SqlCommand(TSqlStatement, sqlConn);
SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);
catParam.SqlDbType = SqlDbType.Structured;
//表值參數的名字叫BulkUdt,在上面的創建測試環境的SQL中有。
catParam.TypeName = "dbo.BulkUdt";
try
{
sqlConn.Open();
if (dt != null && dt.Rows.Count != 0)
{
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConn.Close();
}
}
三、在數據庫建立表值參數類型:
create type dbo.BulkUdt(col1 bigint,col2 nvarchar(10));
四、開始導入數據:
Stopwatch sw = new Stopwatch();
string filePath = @"C:\DB.csv";
DataTable dt = CSVFileHelper.OpenCSV(filePath);
sw.Start();
TableValuedToDB(dt);
sw.Stop();
Trace.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds));