使用 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'}]