psycopg2:无法适应类型"UUID"?



我正在使用psycopg2尝试在表中插入一个条目,其中数据类型为Postgres类型"uuid"。

根据这个页面,我应该可以直接使用 Python 类型 uuid。UUID,如以下代码所示:

uuid_entry = uuid.uuid4()
command = "INSERT INTO MyTable (uuid) VALUES (%s)"
cursor.execute(command, (uuid_entry,))

但是,当我尝试这样做时,它会抛出错误:

ProgrammingError(can't adapt type 'UUID')

关于为什么会发生这种情况的任何想法?谢谢。

正如作者在注释中指出的那样,要将UUID对象传递到游标方法中,必须先调用register_uuid()一次:

import psycopg2.extras
# call it in any place of your program
# before working with UUID objects in PostgreSQL
psycopg2.extras.register_uuid()
# now you can pass UUID objects into psycopg2 functions
cursor.execute("INSERT INTO MyTable (uuid) VALUES (%s)", (uuid.uuid4(),))
# ... and even get it from there
cursor.execute("SELECT uuid FROM MyTable")
value, = cursor.fetchone()
assert isinstance(value, uuid.UUID)
uuid_entry = str(uuid.uuid4()) 

这对我有用。不确定这是否是正确的方法。

最新更新