一、Python与数据库的交互
在没有DB-API
之前,各种数据库之间的应用接口非常混乱,实现各不相同。如果项目需要更换数据库,基本上与数据库相关的代码都要进行改动。
1.1 DB-API
介绍
DB-API
的出现就是为了解决各种数据库之间的应用接口非常混乱问题,python所有的数据接口在一定程度上都要遵循python DB-API规范,它定义了一系列的操作数据库的方式,为各种数据库提供了一致的访问接口,项目中更换数据库变得更加方便
二、python程序操纵MySQL数据库
在python中访问mysql数据需要一个第三方接口pymysql
, 提供的一些列的操纵mysql数据库的函数
2.1 安装
在终端输入如下命令, 进行数据库安装
pip install pymysql
2.2 链接数据库
import pymysql
db_config = {
"host": "127.0.0.1",
"user": "username",
"password": "password",
"database": "database_name",
"charset": "utf8",
"port": 3306
}
connection = pymysql.connect(**db_config) # 链接数据库
2.3 建立游标(connection.cursor())
在程序中, 所有的关于数据的操纵都是通过游标来完成的
cursor = connection.cursor() # 建立游标
2.4 执行sql
语句(cursor)
excutes = cursor.execute(sql) # 不会返回结果,但是会返回影响数据的条数
2.5 查看查询结果(cursor.fetchall()
, cursor.fetchone()
)
results = cursor.fetchall() # 返回一个元组,
result = cursor.fetchone() # 返回查询结果的第一个
2.6 事务
pymysql会主动开启一个事务,执行与数据相关的sql语句不会主动提交
提交事务
connection.commit() # 用连接生成的对象调用
当发生错误时,有必要对事务进行回滚
回滚
connection.rollback() # 用连接生成的对象调用
2.7 关闭游标
cursor.close()
2.8 关闭连接
connection.close()