Psycopg2.programmingerror: can’t adapt type ‘uuid’

psycopg2.ProgrammingError: can’t adapt type ‘uuid’

This error occurs when trying to insert or update a column with a UUID (Universally Unique Identifier) value using the psycopg2 library.

The ‘can’t adapt type’ error suggests that psycopg2 does not have a built-in way to handle the UUID datatype by default.

To resolve this error, you can use the uuid.UUID class from the Python standard library to convert the UUID value to a format that psycopg2 can handle.

Here’s an example of using the uuid.UUID class to adapt a UUID value before inserting it into a PostgreSQL database:

import psycopg2
import uuid

conn = psycopg2.connect(database="your_database", user="your_user", password="your_password", host="your_host", port="your_port")

cur = conn.cursor()

# Generate a UUID value
uuid_value = uuid.uuid4()

# Adapt the UUID value using the uuid.UUID class
adapted_uuid = uuid.UUID(uuid_value)

# Insert the adapted UUID value into the database
cur.execute("INSERT INTO your_table (uuid_column) VALUES (%s)", (adapted_uuid,))
conn.commit()

cur.close()
conn.close()
    

Leave a comment