1

我有一个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

在 MySQL 中存储col6为:

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

2 回答 2

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 );
于 2012-12-20T01:24:23.610 回答
0

这可以通过使用 Excel 宏来实现。使用以下步骤:

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

宏代码是:

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

于 2012-12-27T18:54:48.557 回答