我在尝试bcp 使用Python的csv.writer生成的.csv文件时遇到了EOF问题。我已经做了很多谷歌搜索,但没有运气,所以我转向你们在SO
这是错误消息(在 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)
我在文本编辑器中查看了临时.csv文件,没有看到任何奇怪的EOF或其他控制字符。此外,我查看了其他.csv文件进行比较,似乎没有 bcp 正在寻找的标准化 EOF。
另外,是的,这是黑客,拉下结果集,将其写入磁盘,然后使用 bcp 将其重新上传到数据库。我必须这样做,因为SQLAlchemy不支持同一execute()命令中的多行语句(又名DDL和DML)。此外,此连接与Sybase db连接,该数据库不支持SQLAlchemy出色的ORM:((这就是我首先使用 execute() 的原因)
我所知,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()