是否有 Python 中的 CSV Quotechar 函数适合批量插入 MS SQL 服务器?

IS there a CSV Quotechar function as in Python suitable for Bulk Insert into MS SQL Server?

使用 quotechar '|' 读写 CSV在 Python

下面的 csv 格式允许通过 Python 读取和写入包含指定分隔符(在本例中为“,”)的列的文件。在本例中,“,”位于第二个条目的 B 值之间。

AAAAA, |B,BB|, CCC

以下 Python 代码可用于,例如将行写入文件:

    with open(self.base_uri + filename, 'w') as f:
            writer = csv.writer(f,
                                delimiter=',',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)

            for row in data_list:
                writer.writerow(row)

批量插入 MS SQL 服务器的困难

当尝试使用 csv.file 在 MS SQL 服务器中应用批量插入时,每一行都会发生错误,其中包含一个引号:

take a look here

到目前为止我使用的 SQL 代码如下所示:

bulk insert DATABASE
from 'C:\Users\XX\Documents\sample.csv'
with
(
rowterminator='\n',
fieldterminator=','
)

您对如何解决此问题有任何想法吗? MS SQL 服务器中 Python 中的 quotechar 是否有任何等价物?


关于该主题的一些问题: Bulk insert with text qualifier in SQL Server

我猜你需要 FIELDQUOTE:

Specifies a character that will be used as the quote character in the CSV file. If not specified, the quote character (") will be used as the quote character as defined in the RFC 4180 standard.

bulk insert DATABASE
from 'C:\Users\XX\Documents\sample.csv'
with
(
rowterminator='\n',
fieldterminator=',',
fieldquote = '|'
)

如果您使用的版本低于 2017,您可以使用引号等于 " 而不是管道符号来生成 CSV。

您可以尝试格式文件:如果您在第二列上应用了引号... [csvfile] 包含 AAAAA,"B,BB",CCC

Create Table csvfile
(
f1 VarChar(10),
f2 VarChar(10),
f3 VarChar(10)
)

BULK INSERT csvfile   
     FROM 'c:\downloads\sample.csv'   
     WITH (FORMATFILE = 'c:\downloads\sample.fmt'); 

sample.fmt

14.0
3
1       SQLCHAR             0       10      ",\""    1     f1       SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       10      "\","    2     f2       SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       10      "\r\n"   3     f3       SQL_Latin1_General_CP1_CI_AS

根据@Lukasz Skoda 的回答,我找到了另一个解决方案。 我已将定界符设置为管道 (|) 并将引号设置为 (")。感谢所有试图帮助我的人!