Python 连接 PostgreSQL 数据库

本文测试环境为Windows 7和PostgreSQL 10.3。

首先检查安装psycopg2。

pip install psycopg2

创建数据库连接,执行数据库语句。

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()

数据插入实例。

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()

猜你喜欢

转载自my.oschina.net/u/1011130/blog/1813990