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

Res*_*ens 9 uuid psycopg2 python-3.x

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

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

uuid_entry = uuid.uuid4()
command = "INSERT INTO MyTable (uuid) VALUES (%s)"
cursor.execute(command, (uuid_entry,))
Run Code Online (Sandbox Code Playgroud)

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

ProgrammingError(can't adapt type 'UUID')
Run Code Online (Sandbox Code Playgroud)

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

And*_*kin 10

正如作者在评论中指出的,要将 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)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您还必须添加“import psycopg2.extras”才能注册 UUID。 (2认同)

小智 4

uuid_entry = str(uuid.uuid4()) 
Run Code Online (Sandbox Code Playgroud)

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

  • @noone392 - 我认为注册它的一个优点是,然后从 UUID 字段中选择值将其返回为本机 uuid.UUID 对象,而不是字符串。 (3认同)