python postgresql fetcha code example
Example 1: psycopg2 query
>>> import psycopg2
>>> conn = psycopg2.connect("dbname=test user=postgres")
>>> cur = conn.cursor()
>>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
>>> cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
... (100, "abc'def"))
>>> cur.execute("SELECT * FROM test;")
>>> cur.fetchone()
(1, 100, "abc'def")
>>> conn.commit()
>>> cur.close()
>>> conn.close()
Example 2: postgresql psycopg2 select single value
import psycopg2
import sys
con = None
try:
con = psycopg2.connect(database='testdb', user='postgres',
password='s$cret')
cur = con.cursor()
cur.execute('SELECT version()')
version = cur.fetchone()[0]
print(version)
except psycopg2.DatabaseError as e:
print(f'Error {e}')
sys.exit(1)
finally:
if con:
con.close()