使用Copy_from命令将字典值复制到表中

2 投票
1 回答
1283 浏览
提问于 2025-04-16 16:11

我想把存储在字典里的值插入到一个表格中。这个字典里有1000000个值。

我的字典示例是:

 mydictationary: {"a":1; "b":2; "c":3; "d":4}

我想使用copy_from命令(psycopg2库)把这些值复制到表格里。大概是这样的:

cur.copy_from (mydictationary, myTable)

但是,能不能用copy_from命令来从字典里复制值呢?我想用copy_from命令,因为这可能比使用SQL插入语句要快。

1 个回答

2

正常的做法是这样的:

cur.executemany('INSERT INTO myTable (key, value) VALUES (%s, %s)', mydictionary.items())

如果你坚持要使用 StringIO 的话:

import StringIO
dictFile = StringIO.StringIO()
for item in dictionary.iteritems():
    dictFile.write("%s\t%s\n"%item)
cur.copy_from(dictFile, 'myTable')

撰写回答