2.3 KiB
2.3 KiB
In [12]:
import psycopg2 conn = psycopg2.connect( host="127.0.0.1", database="python", user="postgres", password="postgres", connect_timeout=3, ) cur = conn.cursor()
In [20]:
# cur.execute('create table test(id SERIAL, body TEXT)') for i in range(10): txt = f"have a nice day {i}" sql = "insert into test(body) values (%s) returning id;" cur.execute(sql, (txt,)) id = cur.fetchone()[0] print(f'new id {id}') conn.commit() cur.execute("select count(*) from test;") row = cur.fetchall() if row is None: print("No rows retrieved") else: print(row)
new id 66 new id 67 new id 68 new id 69 new id 70 new id 71 new id 72 new id 73 new id 74 new id 75 [(56,)]
In [18]:
cur.execute("select count(*) from test;") row = cur.fetchone() if row is None: print("No rows retrieved") else: print(row)
(36,)
In [21]:
cur.close()