For the following code:
with psycopg.connect(host="host_name", dbname="db_name", user="user", password="pass") as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM table_name")
res = cur.fetchall()
print(res)
Everything is working fine, but if I try to insert values by replacing
cur.execute("SELECT * FROM table_name")
with
cur.execute("INSERT INTO table_name (column_1, column_2) VALUES (%s, %s)", ("a","b"))
I am getting the following error "the last operation didn't produce a result" what can cause it?
CodePudding user response:
Two ways to handle this:
import psycopg2
con = psycopg2.connect(database="test", host='localhost', user='postgres')
cur = con.cursor()
cur.execute("insert into animals values(24, 'fair', 'cat')")
cur.rowcount
1
cur.execute("insert into animals values(34, 'good', 'dog') returning id")
cur.fetchone()
(34,)
The first way returns the number of rows affected by the operation per Cursor.
The second way returns the id
field so there is actually a result.
CodePudding user response:
In case of insert operations res = cur.fetchall()
is redundant. The error code is self-explanatory here.
try:
cur.execute("INSERT INTO table_name (column_1, column_2) VALUES (%s, %s)", ("a","b"))
except:
print('error')