Python PostgreSQL使用copy_from将COPY对象列表添加到表中

时间:2015-06-14 17:46:22

标签: postgresql python-2.7 postgresql-copy

我正在使用Python 2.7psycopg2连接到我的数据库服务器(PostgreSQL 9.3),我(产品类)的对象列表包含我要插入的项目

products_list = []
products_list.append(product1)
products_list.append(product2)

我想使用copy_from将此产品列表插入到产品表中。我尝试了一些教程,我将产品列表转换为CSV格式时遇到问题,因为这些值包含单引号,新行,制表符和双引号。例如(产品描述):

<div class="product_desc">
    Details :
    Product's Name : name
</div>

转义通过在任何单引号之前添加单引号来破坏HTML代码,所以我需要使用保存方式将列表转换为CSV以复制它吗?或使用任何其他方式插入列表而不将其转换为CSV格式??

1 个答案:

答案 0 :(得分:0)

我想通了,首先我创建了一个将我的对象转换为csv行的函数

import csv

@staticmethod
def adding_product_to_csv(item, out):
writer = csv.writer(out, quoting=csv.QUOTE_MINIMAL,quotechar='"',delimiter=',',lineterminator="\r\n")
writer.writerow([item.name,item.description])

然后在我的代码中,我使用Python IO创建了一个csv文件,将数据存储到COPY中,并使用我之前的函数将每个对象存储在csv文件中:

file_name = "/tmp/file.csv"
myfile = open(file_name, 'a')
for item in object_items:
    adding_product_to_csv(item, myfile)

现在我创建了CSV文件,并且已准备好使用copy_from中存在的psycopg2进行复制:

# For some reason it needs to be closed before copying it to the table
csv_file.close()
cursor.copy_expert("COPY products(name, description) from stdin with delimiter as ',' csv QUOTE '\"' ESCAPE '\"' NULL 'null' ",open(file_name))
conn.commit()
# Clearing the file
open(file_name, 'w').close()

它现在正在工作。