首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >psycopg2:无法适配类型'UUID'?

psycopg2:无法适配类型'UUID'?
EN

Stack Overflow用户
提问于 2018-06-29 23:31:19
回答 2查看 5.7K关注 0票数 10

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

根据this page的说法,我应该能够直接使用Python类型uuid.UUID,如以下代码所示:

代码语言:javascript
运行
复制
uuid_entry = uuid.uuid4()
command = "INSERT INTO MyTable (uuid) VALUES (%s)"
cursor.execute(command, (uuid_entry,))

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

代码语言:javascript
运行
复制
ProgrammingError(can't adapt type 'UUID')

你知道为什么会发生这样的事情吗?谢谢。

EN

回答 2

Stack Overflow用户

发布于 2019-12-10 21:10:21

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

代码语言:javascript
运行
复制
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)
票数 11
EN

Stack Overflow用户

发布于 2019-09-03 23:16:53

代码语言:javascript
运行
复制
uuid_entry = str(uuid.uuid4()) 

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51105100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档