psycopg2:无法适应类型“ UUID”?

时间:2018-06-29 15:31:19

标签: python-3.x uuid psycopg2

我正在使用psycopg2尝试将条目插入到数据类型为Postgres类型'uuid'的表中。

根据this page,我应该能够直接使用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')

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

2 个答案:

答案 0 :(得分:0)

uuid_entry = str(uuid.uuid4()) 

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

答案 1 :(得分:0)

正如作者在评论中指出的那样,要将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)