1 数据库编程接口
1.1 连接对象
数据库连接对象主要提供获取数据库游标对象和提交/回滚事务的方法,以及关闭数据库连接。
connect()
返回连接对象
连接对象方法:
方法名 | 说明 |
---|---|
close() | 关闭数据库连接 |
commit() | 提交事务 |
rollback() | 回滚事务 |
cursor() | 获取游标对象,操作数据库,如执行DML操作,调用存储过程等 |
commit()方法用于提交事务,事务主要用于处理数据量大、复杂度高的数据。
1.2 游标对象
游标对象(Cursor Object)代表数据库中的游标,用于指示抓取数据操作的上下文。主要提供执行SQL语句、调用存储过程、获取查询结果等方法。
2 使用SQLite
2.1 创建数据库文件
操作数据库流程
import sqlite3
# 连接到SQLite数据库
# 数据库文件是data.db,如果文件不存在,会自动在当前目录创建
conn = sqlite3.connect('data.db')
# 创建一个Cursor
cursor = conn.cursor()
# 执行一条SQL语句,创建user表
cursor.execute('create table user(id int(10) primary key, name varchar(20))')
# 关闭游标
cursor.close()
# 关闭Connection
conn.close()
2.2 操作SQLite
1. 新增用户数据信息
insert into 表名(字段名1, 字段名2, ..., 字段名n) values(字段值1, 字段值2, ..., 字段值n)
import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
# 插入一条记录
cursor.execute('insert into user (id, name) values ("1", "yourname")')
cursor.close()
# 提交事务
conn.commit()
conn.close()
2. 查看用户数据信息
select 字段名1, 字段名2, ... from 表名 where 查询条件
- fetchone(): 获取查询结果集中的下一条记录
- fetchmany(size): 获取指定数量的记录
- fetchall(): 获取结构集的所有记录
import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
# 执行查询语句
# 使用占位符的方式可以避免SQL注入的风险
cursor.execute(‘select * from user where id > ?’, (1,))
# 获取查询结果
result = cursor.fetchone()
cursor.close()
conn.close()
3. 修改用户数据信息
update 表名 set 字段名 = 字段值 where 查询条件
import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
# 修改
cursor.execute(‘update user set name = ? where id = ?‘, ('zt',1))
cursor.close()
# 提交事务
conn.commit()
conn.close()
4. 删除用户数据信息
delete from 表名 where 查询条件
import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
# 修改
cursor.execute('delete from user where id = ?',(1,))
cursor.close()
# 提交事务
conn.commit()
conn.close()
3 使用MySQL
3.1 安装PyMySQL
由于MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。
pip install PyMySQL
3.2 连接数据库
import pymysql
# 打开数据库连接,(主机名或IP;用户名;密码;数据库名称)
db = pymysql.connect("localhost", "root", "root", "dbname")
# 创建一个游标对象
cursor = db.cursor()
# 查询
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
db.close()