postgresql批量插入copy_from()的使用

在批量插入postgresql时想使用同Mysql的语法时发现并不能使用:

cursor.executemany("INSERT INTO persons VALUES (%d, %s, %s)",[(1, 'John Smith', 'John Doe'),(2, 'Jane Doe', 'Joe Dog'),(3, 'Mike T.', 'Sarah H.')])
难道只能写成这样吗:
insert into A values(**********),(*************),(*****************)
但是这种方法及麻烦而且还不快
后发现了copy_from()这个神奇的方法!
在参考:https://blog.csdn.net/rongyongfeikai2/article/details/17935139 这位仁兄的博客后一直失败,提示缺少字段.这就很难受了,查阅所有百度的资料无解,大部分都是来回抄袭,毫无新意,这里又忍不住要吐槽百度了.
只能去Google看看了,进入pg的官网才豁然开朗
http://initd.org/psycopg/docs/cursor.html


COPY_FROM说明:

copy_fromfiletablesep =' t'null ='\ N'size = 8192columns = None 
类似文件的目标文件中读取数据将它们附加到名为table的表中
  • file - 从中读取数据的类文件对象。它必须具有 read()readline()方法。
  • table - 要将数据复制到的表的名称。
  • sep - 文件中预期的列分隔符。默认为选项卡。
  • null - NULL文件中的文本表示。默认为两个字符串N
  • size - 用于从文件中读取的缓冲区的大小。
  • columns - 可以使用要导入的列的名称进行迭代。长度和类型应与要读取的文件的内容相匹配。如果未指定,则假定整个表与文件结构匹配。

例:
import StringIO
>>> f = StringIO("42	foo
74	bar
") 
>>> cur.copy_from(f, 'test', columns=('num', 'data')) 
>>> cur.execute("select * from test where id > 5;") 
>>> cur.fetchall() [(6, 42, 'foo'), (7, 74, 'bar')]

注意:

表的名称未引用:如果表名包含大写字母或特殊字符,则必须使用双引号引用:
cur.copy_from(f, '"TABLE"')

不得不说上面哪位仁兄的不严谨性了,在批量插入的每个数据之间用<	>分割,在一条数据的末尾用<
>分割.

 附本人代码段:

tap = (indent_num, it.get(u'商品编码'),it.get(u'商品名称'),it.get(u'批发价'),it.get(u'零售指导价'),it.get(u'需求量'),it.get(u'订购量'),it.get(u'金额'),it.get(u'预计盈利'),cigarette_price)
values_list.append('	'.join(tap))
s = ''
for value in values_list:
s += value + ' '
cur = self.conn.cursor()
try:
# cur.executemany(insert_sql)
cur.copy_from(StringIO.StringIO(s), table,
columns=('indent_num', 'commodity_code', 'commodity_name', 'rade_price', 'guidance_price',
'requirement', 'order_quantity','amount_of_money','wholesale_price','cigarette_price'))
except Exception as e:
raise e
finally:
self.conn.commit()
print 'done'
原文地址:https://www.cnblogs.com/fanjp666888/p/10939342.html