我有一个Person
,id
,fname
和lname
的课程。我的程序将有一大堆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__
以分别返回id
,fname
和lname
,以便查询变为:
insert into persons(id, fname, lname) values (1, 'test1', 'test1')...
答案 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)
不确定这是否是推荐的方法,所以我将其保持开放状态,以希望有人听到。