【问题标题】:psycopg2: Can't adapt type 'UUID'?psycopg2:无法适应类型“UUID”?
【发布时间】:2018-06-29 15:31:18
【问题描述】:

我正在使用 psycopg2 尝试将条目插入到数据类型为 Postgres 类型“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')

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

【问题讨论】:

  • 您是否能够在调试器中验证uuid_entry?您是否能够成功地查询具有给定 uuidinitd.org/psycopg/docs/extras.html#adapt-uuid 的行?
  • @ShawnMehan 嗯,似乎 psycopg2.extensions.adapt(my_uuid).getquoted() 的输出在我的情况下略有不同:b"'2d10d790-f2de-4de5-aaba-7095e04f39cb '::uuid"。它似乎被包裹在 b"..." 中。
  • b 告诉您它是binary string。但是您应该尝试从您的数据库中获取另一个 id 并提取该 id 并将其类型和格式与您正在制作的进行比较。确保它们在 python 中的外观相似。
  • @ShawnMehan 似乎我能够在调用cursor.execute 之前使用psycopg2.extras.register_uuid() 解决问题。

标签: python-3.x uuid psycopg2


【解决方案1】:

正如作者在 cmets 中所说,要将 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)

【讨论】:

  • 注意,在注册 UUID 之前,您还必须添加 import psycopg2.extras
【解决方案2】:
uuid_entry = str(uuid.uuid4()) 

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

【讨论】:

  • 这个答案很完美。不确定注册它的目的或优势。
  • @noone392 - 我认为注册它的一个优点是,然后从 UUID 字段中选择值会将其作为本机 uuid.UUID 对象返回,而不是字符串。
猜你喜欢
  • 2018-11-10
  • 2021-08-08
  • 2019-11-10
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
相关资源
最近更新 更多