我正在使用psycopg2尝试在数据类型为Postgres type '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')
你知道为什么会发生这样的事情吗?谢谢。
发布于 2019-12-10 21:10:21
正如作者在评论中指出的,要将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)
发布于 2019-09-03 23:16:53
uuid_entry = str(uuid.uuid4())
这对我很有效。不确定这是否是正确的方法。
https://stackoverflow.com/questions/51105100
复制相似问题