简体   繁体   中英

Python module psycopg2 cannot find a reference

I installed psycopg2 module because I want to send blob file to database. But I'm getting an error.

AttributeError: 'psycopg2.extensions.connection' object has no attribute 'execute'

Here is my code, what's the problem?

conn = psycopg2.connect(database='SECRET', user='SECRET',
                            password='SECRET', host='SECRET',
                            port=5432)
cursor = conn.cursor()
cursor.execute("SELECT gen_random_uuid();")
id = cursor.fetchone()[0]

drawing = open("cat.jpg", 'rb').read() 
conn.execute("INSERT INTO files(uuid, filename, data) VALUES(%s,%s,%s)", (id, "cat.jpg", 
psycopg2.Binary(drawing)))
conn.commit()

The second execute uses the connection instead of the cursor. Replace this line:

conn.execute("INSERT INTO files(uuid, filename, data) VALUES(%s,%s,%s)", (id, "cat.jpg", psycopg2.Binary(drawing)))

with:

cursor.execute("INSERT INTO files(uuid, filename, data) VALUES(%s,%s,%s)", (id, "cat.jpg", psycopg2.Binary(drawing)))

should fix the problem.

you should install the package pip install psycopg2-binary following the installation page and I quote

You can also obtain a stand-alone package, not requiring a compiler or external libraries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM