本文测试环境为Windows 7和PostgreSQL 10.3。数据库
首先检查安装psycopg2。测试
pip install psycopg2
建立数据库链接,执行数据库语句。fetch
import psycopg2 #建立数据库链接,数据库配置信息根据实际状况填写 LocalPostgreSQLConnection = psycopg2.connect( host="127.0.0.1", port="5432",database="test", user="root", password="root") cur = LocalPostgreSQLConnection.cursor() cur.execute('''create table company (id int primary key not null, name text not null, age int not null, address char(50), salary real);''') #提交事务,未提交数据库没法查询结果 LocalPostgreSQLConnection.commit() #关闭数据库链接 LocalPostgreSQLConnection.close()
数据插入实例。code
import psycopg2 LocalPostgreSQLConnection=psycopg2.connect(host="127.0.0.1",port="5432",database="test",user="root",password="root") cur=LocalPostgreSQLConnection.cursor() cur.execute(''' insert into company values(1,'Bill',22,'New York',22.50); ''') LocalPostgreSQLConnection.commit() LocalPostgreSQLConnection.close()
简单查询。事务
import psycopg2 LocalPostgreSQLConnection=psycopg2.connect(host="127.0.0.1",port="5432",database="test",user="root",password="root") cur=LocalPostgreSQLConnection.cursor() cur.execute("select id, name, address, salary from company") rows = cur.fetchall() #cursor.fetchall() 这个例程获取全部查询结果(剩余)行,返回一个列表。空行时则返回空列表。 for row in rows: print("ID = ", row[0]) print("NAME = ", row[1]) print("ADDRESS = ", row[2]) print("SALARY = ", row[3], "\n") print("select database successfully") LocalPostgreSQLConnection.commit() LocalPostgreSQLConnection.close()