使用 psycopg2 从 python 访问 PostgreSQL

你可以在这里找到驱动程序的描述。

简单的例子是:

import psycopg2

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

conn = psycopg2.connect("dbname={} host={} user={} password={}".format(
                         db_name,  db_host, 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())

将导致:

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