PostgreSQL自学笔记:与python交互
与python交互教程
原文地址:https://www.yiibai.com/html/postgresql/2013/080998.html
1. Python psycopg2 模块APIs
- 连接到数据库
psycopg2.connect(database='test',user='postgres', password='520520',host='127.0.0.1',port='5432')
-
创建光标
connection.cursor()
-
执行SQL语句
cursor.execute(sql[,optional parameters])
-
提交当前事务
connection.commit()
-
回滚
connection.rollback()
-
关闭数据库
connection.close()
-
提取查询结果的下一行
cursor.fetchone()
-
取出下一组的查询结果的行数,返回一个列表
cursor.fetchmany()
-
获取所有查询结果(剩余),返回一个列表
cursor.fetchall()
2. 创建表
import psycopg2
# 连接到数据库
conn = psycopg2.connect(database='test',user='postgres',
password='520520',host='127.0.0.1',port='5432')
print('连接成功')
# 创建光标
cur = conn.cursor()
s = '''
create table pythonTest(
e_no int primary key not null,
e_name varchar(50) not null,
e_gender char(2) not null,
dept_no int not null,
e_job varchar(100) not null,
e_salary smallint,
hireDate date
)
'''
cur.execute(s)
conn.commit()
print('建表成功')
conn.close()
3. 插入操作
import psycopg2
# 连接到数据库
conn = psycopg2.connect(database='test',user='postgres',
password='520520',host='127.0.0.1',port='5432')
print('连接成功')
# 创建光标
cur = conn.cursor()
s = '''
insert into pythonTest
values(1001,'赵1','m',20,'会计',800,'2005-11-12'),
(1002,'钱2','f',30,'推销员',1600,'2003-05-12'),
(1003,'孙3','f',30,'推销员',1250,'2005-05-12'),
(1004,'李4','m',20,'经理',2975,'1998-05-18'),
(1005,'周5','m',30,'推销员',1250,'2001-06-12'),
(1006,'吴6','f',30,'经理',2850,'1997-02-15'),
(1007,'郑7','f',10,'经理',2450,'2002-09-12'),
(1008,'王8','m',20,'分析师',3000,'2003-05-12'),
(1009,'冯9','m',10,'董事长',5000,'1995-01-01'),
(1010,'陈10','f',30,'推销员',1500,'1997-10-12'),
(1011,'褚11','f',20,'会计',1100,'1999-10-05'),
(1012,'卫12','m',30,'会计',950,'2008-06-15');
'''
cur.execute(s)
conn.commit()
print('插入成功')
conn.close()
4. 查询操作
import psycopg2
# 连接到数据库
conn = psycopg2.connect(database='test',user='postgres',
password='520520',host='127.0.0.1',port='5432')
print('连接成功')
# 创建光标
cur = conn.cursor()
s = '''
select e_name,e_job from pythonTest
'''
cur.execute(s)
conn.commit()
rows = cur.fetchall()
for i in rows:
print(i)
conn.close()
5. 修改操作
import psycopg2
# 连接到数据库
conn = psycopg2.connect(database='test',user='postgres',
password='520520',host='127.0.0.1',port='5432')
print('连接成功')
# 创建光标
cur = conn.cursor()
s = '''
update pythonTest set e_job='分析师' where e_name='卫12'
'''
cur.execute(s)
conn.commit()
print('修改成功')
conn.close()
6. 删除操作
import psycopg2
# 连接到数据库
conn = psycopg2.connect(database='test',user='postgres',
password='520520',host='127.0.0.1',port='5432')
print('连接成功')
# 创建光标
cur = conn.cursor()
s = '''
delete from pythonTest where e_no=1011
'''
cur.execute(s)
conn.commit()
print('删除成功')
conn.close()