使用Python连接到PostgreSQL

安装

pip install psycopg2
pip install psycopg2-binary

进行测试套件

python -c "from psycopg2 import tests; tests.unittest.main(defaultTest='tests.test_suite')" --verbose

通过提前准备测试用的数据库,可以执行以下操作:
createdb -E utf8 psycopg2_test

基本模块的使用方法

事先创建测试用的数据库

创建数据库 -E utf8 test
启动Python的交互模式。


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()
conn.commit()
cur.close()
conn.close()

我已经确认了表的创建(CREATE)、数据的插入(INSERT)以及数据的查询(SELECT)。

请参考

Psycopg是用于Python的PostgreSQL数据库适配器。

bannerAds