我有一个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.
答案 0 :(得分:1)
您有两个选择
要求提供有效的RFC 4180 CSV文件,而不是一个不错的文本文件
后跟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宏可以实现这一点。使用以下步骤:
Insert > Module
。Tools > Macro > Macros
运行您的宏。您
应该看到一个名为CSVFile
的宏被选中。单击“运行”。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