具有类对象列表的psycopg2 execute_values

时间:2018-09-28 20:54:54

标签: python psycopg2

我有一个Personidfnamelname的课程。我的程序将有一大堆Person对象,我想将其插入我的PostgreSQL数据库中。

我想通过psycopg2.execute_values方法做到这一点,该方法要求为我的班级定义__getitem__

__getitem__当前返回tuple(id, fname, lname),这导致pscopg2.execute_values试图执行:insert into persons(id, fname, lname) values ((1, 'test1', 'test1'))...

import psycopg2.extras


class Person:
    def __init__(self, id, fname, lname):
        self.id = id
        self.fname = fname
        self.lname = lname

    def __len__(self):
        return 1

    def __getitem__(self, item):
        return self.id, self.fname, self.lname


dsn = "user=my_user host=localhost port=5432 dbname=my_db"
query = "insert into persons(id, fname, lname) values %s"

p1 = Person(1, 'test1', 'test1')
p2 = Person(2, 'test2', 'test2')

records = list()
records.append(p1)
records.append(p2)
with psycopg2.connect(dsn=dsn) as conn:
    with conn.cursor() as cursor:
        psycopg2.extras.execute_values(cursor, query, records, template=None, page_size=1000)

psycopg2.ProgrammingError: INSERT has more target columns than expressions
LINE 1: insert into persons(id, fname, lname) values ((1, 'test1', 'test1'))...
                                ^
HINT:  The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?

使用namedtuple可以做到:

from collections import namedtuple
import psycopg2.extras


Person = namedtuple('Person', ['id', 'fname', 'lname'])

dsn = "user=my_user host=localhost port=5432 dbname=my_db"
query = "insert into persons(id, fname, lname) values %s"

p1 = Person(1, 'test1', 'test1')
p2 = Person(2, 'test2', 'test2')

records = list()
records.append(p1)
records.append(p2)

with psycopg2.connect(dsn=dsn) as conn:
    with conn.cursor() as cursor:
        psycopg2.extras.execute_values(cursor, query, records, template=None, page_size=1000)

但是,我想实现不同的__eq____hash__实现。如果有一种方法可以namedtuple覆盖这些方法,那么我愿意采用这种方法。

否则,如何修改__getitem__以分别返回idfnamelname,以便查询变为:

insert into persons(id, fname, lname) values (1, 'test1', 'test1')...

1 个答案:

答案 0 :(得分:1)

定义__conform__似乎可以解决问题:https://www.python.org/dev/peps/pep-0246/

import psycopg2.extras
from psycopg2.extensions import AsIs, ISQLQuote


class Person:
    def __init__(self, id, fname, lname):
        self.id = id
        self.fname = fname
        self.lname = lname

    def __len__(self):
        return 1

    def __getitem__(self, key):
        return self

    def __conform__(self, protocol):
        if protocol is ISQLQuote:
            return AsIs("{id}, '{fname}', '{lname}'".format(id=self.id, fname=self.fname, lname=self.lname))

        return None


dsn = "user=my_user host=localhost port=5432 dbname=my_db"
query = "insert into persons(id, fname, lname) values %s"

p1 = Person(1, 'test1', 'test1')
p2 = Person(2, 'test2', 'test2')

records = list()
records.append(p1)
records.append(p2)

with psycopg2.connect(dsn=dsn) as conn:
    with conn.cursor() as cursor:
        psycopg2.extras.execute_values(cursor, query, records, template=None, page_size=1000)

不确定这是否是推荐的方法,所以我将其保持开放状态,以希望有人听到。