类型错误:在字符串格式化 postgres 期间并非所有参数都被转换

问题描述 投票:0回答:3

我尝试将数据添加到数据库(使用psycopg2.connect):

cand = Candidate('test', datetime.now(), '[email protected]', '123123', "21", 'test', 'test', 'test', datetime.now(), "1", "1", 'test', 'M', "18", "2", "2")
db.addCandidate(cand)

我的功能添加:

def addCandidate(self, candidate):
    with self.connection.cursor() as cursor:
        cursor.execute("""INSERT INTO candidate ( name, pub_date, email, tel, age, proff, href, city, last_update, called_count, status, comment, sex, recrut_id, vacancy_id, level)
              VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (candidate.name, candidate.pub_date, candidate.email, candidate.tel,
                             candidate.age, candidate.proff, candidate.href, candidate.city, candidate.last_update, candidate.called_count, candidate.status, candidate.comment, candidate.sex, candidate.recrut_id,
                             candidate.vacancy_id, candidate.level))
        self.connection.commit()

我尝试将数据包装在 str 中,但没有任何改变。 在 pymysql.connect 中工作正常

python postgresql psycopg2
3个回答
0
投票

我无法确定,因为我不知道您的列的类型,但您的日期时间对象的格式可能不正确。您发送的日期时间对象不是正确日期格式的字符串。尝试:

candidate.pub_date.isoformat()

candidate.pub_date.strftime("<proper_format">)

请参阅 http://strftime.org/ 了解格式选项。这可能对你有用。


0
投票

而不是

execute
执行
mogrify
来检查到底发送到服务器的内容:

print cursor.mogrify ("""
    INSERT INTO candidate ( 
        name, pub_date, email, tel, age, proff, href, city, 
        last_update, called_count, status, comment, 
        sex, recrut_id, vacancy_id, level
    ) VALUES (
        %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
    )""", (
        candidate.name, candidate.pub_date, candidate.email,
        candidate.tel, candidate.age, candidate.proff, candidate.href,
        candidate.city, candidate.last_update, candidate.called_count, 
        candidate.status, candidate.comment, candidate.sex, 
        candidate.recrut_id, candidate.vacancy_id, candidate.level
    )
)

0
投票

我解决了我的问题,我写了 15 '%s',而不是 16

© www.soinside.com 2019 - 2024. All rights reserved.