我是Python(和编码)的新手,对尝试使用copy_from的兴趣不胜枚举。
我正在从CSV读取行,对其进行一些处理,然后将其写入SQL。使用普通的INSERT命令要花费很长时间,并且要包含数十万行,因此我想使用copy_from。它确实可以与INSERT一起使用。
[https://www.psycopg.org/docs/cursor.html#cursor.copy_from本示例在每个行的末尾使用制表符作为列分隔符和换行符,因此我相应地制作了每个IO行:
43620929 2018-04-11 11:38:14 30263506 30263503 30262500 0 0 0 0 0 1000 1000 0
这是下面的第一个打印语句的输出:
def copyFromIO(thisOutput):
print(thisOutput.getvalue())
cursor.copy_from(thisOutput, 'hands_new')
thisCommand = 'SELECT * FROM hands_new'
cursor.execute(thisCommand)
print(cursor.fetchall())
hands_new是现有的空SQL表。第二个print语句只是[],因此它没有写入数据库。我怎么了?
很明显,如果可以,我可以使thisOutput更长,有很多行,而不仅仅是一行。
我想我已经弄明白了,所以如果以后有人出于某种原因遇到这个问题:
'thisOutput'格式是错误的,我是通过较小的片段(包括添加'\ t'等)构建的。
copyFromIO(io.StringIO('43620929\t2018-04-11 11:38:14\t30263506\t30263503\t30262500\t0\t0\t0\t0\t0\t1000\t1000\t0\n'))
&我需要copy_from命令中的右列:
def copyFromIO(thisOutput):
print(thisOutput.getvalue())
thisCol = ('pkey', 'created', 'gameid', 'tableid', 'playerid', 'bet', 'pot',
'isout', 'outround', 'rake', 'endstack', 'startstack', 'stppaid')
cursor.copy_from(thisOutput, 'hands_new', columns=(thisCol))
thisCommand = 'SELECT * FROM hands_new'
cursor.execute(thisCommand)
print(cursor.fetchall())