【问题标题】:How to copy 1 column from a CSV file to a SQL database?如何将 1 列从 CSV 文件复制到 SQL 数据库?
【发布时间】:2017-01-04 13:32:37
【问题描述】:

我有一个 CSV 文件,但在使用的文件中没有逗号分隔符。 如何将这些数据复制到我的数据库中?所以 CSV 文件和数据库应该有 1 列。

这是我迄今为止尝试过的:

System.Data.DataTable csvData = new System.Data.DataTable();
try
{
    using (TextFieldParser csvReader = new TextFieldParser(csv_file_path, Encoding.GetEncoding("windows-1250"))) //windows 1250 is de correcte character encoding voor europese characters 
    {
        csvReader.SetDelimiters(new string[] { "," }); //change this maybe to something???
        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); // it return an error here saying that: `System.ArgumentException: Input array is longer than the number of columns in this table`
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);
return csvData;

因此,CSV 的示例是:

test123    
test45,6    
test789

在我的数据库中将是完全相同的值。

【问题讨论】:

  • 抱歉,我不明白您所说的“没有逗号分隔”的 CSV 文件是什么意思。你能提供一个你正在导入的数据的例子吗?
  • @MaurizioPozzobon Ye,现在我再次阅读它确实有点模糊。我正在阅读 CSV,但 CSV 的即时阅读内容不包含任何逗号分隔符,这就是为什么我的数据库文件中只有 1 列的原因。我在我的问题中添加了一个示例
  • 你能调试一下,看看 colFields 中有多少列,我的意思是 fieldData.Length == ??
  • 如果您的文件有这些 |和 - 登录,你需要做更多的工作.. 但是如果它只有 1 个值,它不是 csv,它只是一个文本文件,那么你在加载数据并将其放入 sql 时有什么问题
  • @FacundoLaRocca fieldData.Lenth 取决于读取的每一行。您想知道错误处的 fieldData.Length 是什么吗?

标签: c# sql csv


【解决方案1】:

编辑:阅读关于实际分隔符的评论,所以我更新了下面的代码,虽然不漂亮,但应该给你一个起点

为什么不将文件作为简单的文本文件读取。一次一行并解析预期的语法。

做这样的事情(未经测试,可能无法编译)

string line;
System.Data.DataTable csvData = new System.Data.DataTable();
csvData.Columns.Add("OnlyColumn", typeof(String));
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
    if(line.StartsWith("-"))
        continue;        
    DataRow newRow = csvData.NewRow();
    newRow["OnlyColumn"] = line.Split('|')[1].Trim();
    csvData.Rows.Add(newRow);
}

file.Close();
InsertDataIntoSQLServerUsingSQLBulkCopy(csvData, tablenaam);

【讨论】:

  • 我收到一个错误@if(line.StartsWith('-'))cannot convert from char to string
  • 这工作if (line.StartsWith("-")) continue; 但我收到错误:System.Data.dll 中发生“System.ArgumentException”类型的未处理异常附加信息:列“OnlyColumn”不属于表跨度>
  • 您必须将列添加到数据表中,我已经编辑了示例,但您应该将其视为起点
【解决方案2】:

也许您需要使用换行符而不是逗号作为分隔符。我认为你可以在新行中拥有新的价值观?

【讨论】:

  • 我试过 csvReader.SetDelimiters(new string[] { Environment.NewLine }); csvReader.SetDelimiters(new string[] { "\n" ); ,但这些都没有用。我收到错误:System.ArgumentException: TextfieldParser does not support delimiters that contain end-of-line characters
【解决方案3】:

我认为您可以为此使用StreamReader.ReadLine()

您应该查看此链接以获取 Microsoft 的解释。 https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx

所以应该这样做:

using (StreamReader sr = new StreamReader(csv_file_path)) 
{
    while (sr.Peek() >= 0) 
    {
        csvData.Rows.Add(new string[] {sr.ReadLine()});
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2015-06-19
    • 2022-01-04
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多