Accessing PostgreSQL from Python using psycopg2

suggest change

You can find a description of the driver here.

The quick example is:

import psycopg2
from psycopg2.extras import RealDictCursor

db_host = 'postgres.server.com'
db_port = '5432'
db_un = 'user'
db_pw = 'password'
db_name = 'testdb'

conn = psycopg2.connect("dbname={} host={} port={} user={} password={}".format(
                         db_name, db_host, db_port, db_un, db_pw),
                         cursor_factory=RealDictCursor)
cur = conn.cursor()
sql = 'select * from testtable where id > %s and id < %s'
args = (1, 4)
cur.execute(sql, args)

print(cur.fetchall())

This prints:

[{'id': 2, 'fruit': 'apple'}, {'id': 3, 'fruit': 'orange'}]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents