psycopg2: Can't adapt type 'UUID'?

跟風遠走 提交于 2020-01-24 12:02:08

问题


I am using psycopg2 to try to insert an entry into a table where the type of the data is the Postgres type '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.


回答1:


uuid_entry = str(uuid.uuid4()) 

This works for me. Not sure if it is the right approach.




回答2:


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)


来源:https://stackoverflow.com/questions/51105100/psycopg2-cant-adapt-type-uuid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!