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)
小智 4
uuid_entry = str(uuid.uuid4())
Run Code Online (Sandbox Code Playgroud)
这对我有用。不确定这是否是正确的方法。