您好我有一个应用程序,用户浏览csv文件,csv文件中的数据只能使用BULK INSERT
文本文件看起来像这样
Student_head 201501
student_id code amount
1 salb 10015
2 salb 10016
3 salb 10017
4 c100 4000
5 salb 10022
END
我需要做的是跳过前2行和最后一行。
我应该得到这样的东西:
1 salb 10015
2 salb 10016
3 salb 10017
4 c100 4000
5 salb 10022
我试过这段代码但似乎没有发生任何事情
openFileDialog1.Filter = ".csv file|*.csv*";
openFileDialog1.FilterIndex = 1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.Yes)
{
String file = openFileDialog1.FileName;
using (var reader = new StreamReader(file))
{
string firstLine = reader.ReadLine();
string[] splitedLine = firstLine.Split(';');
string month = splitedLine[1];
}
try
{
string connect = "Data Source=George-PC\\SQLEXPRESS; Initial Catalog=Students; user id =sa; Password=george1";
SqlConnection con = new SqlConnection(connect);
con.Open();
String BulkInsert = "BULK INSERT t_original FROM" +
file + "WITH (FIRSTROW = 3," +
"FIELDTERMINATOR = ''," +
"MAXERRORS = 0," +
"ROWTERMINATOR = '\\n')";
//"UPDATE t_original"+
//"SET month =" + month +
//"WHERE month is null";
SqlCommand bulkCmd = new SqlCommand(BulkInsert, con);
bulkCmd.ExecuteNonQuery();
任何帮助和建议将不胜感激
谢谢
答案 0 :(得分:0)
不要使用SqlCommand
,而是尝试使用SqlBulkCopy
对象。
像...一样的东西。
DataTable table = new DataTable();
//turn your CSV data into a DataTable using your favorite CSV parser.
//My favorite is [`TextFieldParser`][2].
using SqlBulkCopy copier = new SqlBulkCopy(connectionString,
SqlBulkCopyOptions.KeepIdentity Or SqlBulkCopyOptions.KeepNulls) {
// Now set up your column mappings via SqlBulkCopy.ColumnMappings
// Choose a destination table with SqlBulkCopy.DestinationTableName
// execute the copy
copier.WriteToServer(table);
}