Python PostgreSQL 使用 copy_from 将对象列表复制到 table

Python PostgreSQL using copy_from to COPY list of objects to table

我正在使用 Python 2.7psycopg2 连接到我的数据库服务器 (PostgreSQL 9.3) 并且我的对象列表 (Product Class) 包含我的项目想插入

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

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

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

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

我明白了,首先我创建了一个函数来将我的对象转换为 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()

现在可以使用了。