我写了一个程序到SqlBulkCopy将CSV数据导入MYSQL数据库。在函数InsertDataIntoSQLServerUsingSQLBulkCopy中触发一些错误,如下面的快照。
我在下面附上了我的源代码。错误在第54行触发。
using System;
using System.Data;
using Microsoft.VisualBasic.FileIO;
using System.Data.SqlClient;
namespace ReadDataFromCSVFile
{
static class Program
{
static void Main()
{
string csv_file_path = @"C:\Users\source\repos\WindowsService1\WindowsService1\bin\Debug\data.csv";
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Console.WriteLine("Rows count:" + csvData.Rows.Count);
Console.ReadLine();
}
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
**line 54 function static void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData) {
using (SqlConnection dbConnection = new SqlConnection("Data Source=.\SQLEXPRESS; Initial Catalog=MorganDB; Integrated Security=SSPI;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = "table1";
foreach (var column in csvFileData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(csvFileData);
}
}
}
}
}
如果有人能够发现错误,我会非常感激。谢谢!
答案 0 :(得分:2)
您是否对Visual BASIC感到困惑? function
不是C#关键字。将function
替换为private
或public
,具体取决于用例。
此外,您应该可以在包含中使用System.IO
代替Microsoft.VisualBasic.FileIo
。