psycopg2:无法适应“UUID"类型? [英] psycopg2: Can't adapt type 'UUID'?

查看:83
本文介绍了psycopg2:无法适应“UUID"类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using psycopg2 to try to insert an entry into a table where the type of the data is the Postgres type 'uuid'.

根据这个页面,我应该能够直接使用Python类型uuid.UUID,如下代码:

According to this page, I should be able to directly use the Python type uuid.UUID, as in the following code:

uuid_entry = uuid.uuid4()
command = "INSERT INTO MyTable (uuid) VALUES (%s)"
cursor.execute(command, (uuid_entry,))

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

However, when I try to do this, it throws the error:

ProgrammingError(can't adapt type 'UUID')

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

Any ideas on why this is happening? Thanks.

推荐答案

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

As author noted in comments, to pass UUID objects into cursor methods one have to call register_uuid() first once:

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)

这篇关于psycopg2:无法适应“UUID"类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆