1

尝试 bcp 使用 Python 的 csv.writer 生成的 .csv 文件时遇到 EOF 问题。我已经做了很多谷歌搜索但没有运气,所以我求助于你们有帮助的人

这是错误消息(在 subprocess.call() 行上触发):

Starting copy...
Unexpected EOF encountered in BCP data-file.
bcp copy in failed

这是代码:

sel_str = 'select blahblahblah...'
result = engine.execute(sel_str)  #engine is a SQLAlchemy engine instance

# write to disk temporarily to be able to bcp the results to the db temp table
with open('tempscratch.csv','wb') as temp_bcp_file:
    csvw = csv.writer(temp_bcp_file)
    for r in result:
        csvw.writerow(r)
        temp_bcp_file.flush()

# upload the temp scratch file
bcp_string = 'bcp tempdb..collection in @INFILE -c -U username -P password -S DSN'
bcp_string = string.replace(bcp_string,'@INFILE','tempscratch.csv')
result_code = subprocess.call(bcp_string, shell=True)

我在文本编辑器中查看了 tempscratch.csv 文件,没有看到任何奇怪的 EOF 或其他控制字符。此外,我查看了其他 .csv 文件进行比较,并且似乎没有 bcp 正在寻找的标准化 EOF。

此外,是的,这是 hacky,拉下结果集,将其写入磁盘,然后使用 bcp 将其重新上传到数据库。我必须这样做,因为 SQLAlchemy 不支持同一个 execute() 命令中的多行语句(又名 DDL 和 DML)。此外,此连接是与 Sybase db 的,它不支持 SQLAlchemy 的精彩 ORM :((这就是我首先使用 execute() 的原因)

4

1 回答 1

5

据我所知,bcp 默认字段分隔符是制表符“\t”,而 Python 的 csv 编写器默认为逗号。试试这个...

# write to disk temporarily to be able to bcp the results to the db temp table
with open('tempscratch.csv','wb') as temp_bcp_file:
    csvw = csv.writer(temp_bcp_file, delimiter = '\t')
    for r in result:
        csvw.writerow(r)
    temp_bcp_file.flush()
于 2012-05-24T15:42:32.517 回答