如何在将csv文件加载到表中时忽略字段内的逗号

时间:2012-12-20 00:26:10

标签: mysql

我有一个csv文件。我需要将内容加载到表中。某些字段包含逗号,但我在这些字段中遇到错误。该命令截断此逗号中的字段。如何改进我的命令忽略字段值内的逗号。这是我的SQL命令:

LOAD DATA INFILE 'C:/myfile.csv'
IGNORE
INTO TABLE db.table
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
(col1,col2,col3,col4,col5,col6);

编辑:我的csv文件字段未包含在"

编辑:csv中的数据示例:

col1  |  col2  |  col3  |  col4  |  col5  |  col6
------------------------------------------------------------
1111  |  2222  |  3333  |  4444  |  5555  |  firstname, lastname

col6中存储在MySQL中作为:

"firstname, lastname" .. followed by all the next fields until the column is filled and truncated.

2 个答案:

答案 0 :(得分:1)

您有两个选择

选项1

要求提供有效的RFC 4180 CSV文件,而不是一个不错的文本文件

选项2

后跟LOAD DATA INFILE语法,你可以这样做

LOAD DATA INFILE 'C:/myfile.csv'
IGNORE
INTO TABLE db.table
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
( col1, col2, col3, col4, col5, @firstname, @lastname )
SET col6 = CONCAT_WS( ' ', @firstname, @lastname );

答案 1 :(得分:0)

使用Excel宏可以实现这一点。使用以下步骤:

  1. 打开Visual Basic编辑器(Alt + F11)。
  2. 在编辑器中,转到:Insert > Module
  3. 粘贴下面显示的宏
  4. 关闭脚本编辑器
  5. 转到Excel并从Tools > Macro > Macros运行您的宏。您 应该看到一个名为CSVFile的宏被选中。单击“运行”。
  6. 您将看到Save As窗口。输入工作表的名称并保存 它。新表将为每个字段添加“”。
  7. 宏代码是:

    Sub CSVFile()
    Dim SrcRg As Range
    Dim CurrRow As Range
    Dim CurrCell As Range
    Dim CurrTextStr As String
    Dim ListSep As String
    Dim FName As Variant
    FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
    ListSep = Application.International(xlListSeparator)
      If Selection.Cells.Count > 1 Then
        Set SrcRg = Selection
      Else
        Set SrcRg = ActiveSheet.UsedRange
      End If
    Open FName For Output As #1
    For Each CurrRow In SrcRg.Rows
      CurrTextStr = ìî
    For Each CurrCell In CurrRow.Cells
      CurrTextStr = CurrTextStr & """" & CurrCell.Value & """" & ListSep
    Next
    While Right(CurrTextStr, 1) = ListSep
      CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
    Wend
    Print #1, CurrTextStr
    Next
    Close #1
    End Sub
    

    参考:http://www.markinns.com/articles/full/export_excel_csvs_with_double_quotes