我想将 CSV 文件中的数据添加到 SQL Server 中表的列中。我的代码正在运行,但数据未到达该列。
private void btCode_Click(object sender, RoutedEventArgs e)
{
//string constring = "Data Source=.;Initial Catalog=*******;Integrated Security=True";
string filepath = "C:\\code.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string Code in value)
{
dt.Columns.Add(new DataColumn(Code));
}
尽管:
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(sc.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "CodesTable";
bc.BatchSize = dt.Rows.Count;
sc.Open();
bc.WriteToServer(dt);
bc.Close();
sc.Close();