ADO.NET2.0から備わったSqlBulkCopyを使って、Odbc経由で開いたCSVファイルをテーブルに一括読み込みするチョイ技です。
private void ImportCsvData(string fileFullName,SqlConnection con) { int affected = 0; System.IO.FileInfo fi = new System.IO.FileInfo(fileFullName); using (System.Data.Odbc.OdbcConnection odbccon = new System.Data.Odbc.OdbcConnection(@"DRIVER={Microsoft Text Driver (*.txt; *.csv)};DefaultDir=" + fi.DirectoryName)) { odbccon.Open(); System.Data.Odbc.OdbcCommand cmd = odbccon.CreateCommand(); cmd.CommandText = "select * from " + fi.Name; System.Data.Odbc.OdbcDataReader reader = cmd.ExecuteReader(); using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(con)){ bcp.DestinationTableName = "TargetTableName"; bcp.NotifyAfter = 1000; bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied); bcp.WriteToServer(reader); affected =bcp.BatchSize; } } } private void bcp_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Console.WriteLine("インポート実行中:" + (int)e.RowsCopied + "件"); }
■呼び出し方
int affected = ImportCsvData("\\server\test\file.csv",con);