Python数据库:嵌入式MySQL
- Python访问MySQL的库函数
- PyMySQL
- 安装PyMySQL
- 快速上手以及代码上下文
- PyMySQL常见语法
- 1. 导包
- 2.连接数据库 connect
- 3. 创建访问对象 cursor
- 4. 下达命令 cursor.execute
- 5. 接收结果 cursor.fetch*
- 6.事务的用法
- 7. 关闭mysql链接 close
Python访问MySQL的库函数
python访问MySQL主要有两种访问方式
一种是PyMySQL
,另一种是mysql-connector
我主要用的是PyMySQL
,后续两种都会尝试更新啦。
PyMySQL
安装PyMySQL
安装python,配置pip相关参数,然后执行下述的下载
pip3 install PyMySQL
快速上手以及代码上下文
import pymysql# 连接数据库
db = pymysql.connect(host='localhost',user='root',password='123456',database='dnf')
# 创建访问对象
cursor = db.cursor()sql = "SELECT * FROM `key`"
# 下发命令
cursor.execute(sql)# 接受结果
results = cursor.fetchall()print (results)
print (type(results))cursor.execute(sql)
results = cursor.fetchone()
print(results)
results = cursor.fetchone()
print(results)# 关闭数据库连接
db.close()
PyMySQL常见语法
1. 导包
import pymysql
2.连接数据库 connect
# 语法
pymysql.connect(host, user, password, database)# 实例
db = pymysql.connect(host='localhost',user='user',password='123456',database='dna')
3. 创建访问对象 cursor
pymysql中,所有命令都通过cursor对象进行命令下发,这种设计模式是命令模式设计理念。对外统一接口。对内处理逻辑。使用时候,先创建cursor对象。
cursor = db.cursor()
4. 下达命令 cursor.execute
通过cursor对象的execute方法进行命令下发,所有的命令都可以通过该方法执行。接口统一
# 执行命令
cursor.execute(mysql_cmd: str)# 范例
cursor.execute("SELECT VERSION()")
cursor.execute("SELECT * FROM employee_tbl")
5. 接收结果 cursor.fetch*
cursor对象接收到execute的返回值会默认保存在cursor中,我们可以通过fetchone()
和fetchall()
进行访问。如果我们把数据表按行列形式展开,每一列表示数据表的一个field内容,那么每一行表示一个结果集。
fetchone()
: 该方法可以获取一行的结果集查询,多次调用则会返回依次返回下一个数据行的结果集。类似readline函数。结果集以集合(元组,tuple)的形式展示fetchall()
: 接收全部的返回结果行。返回结果是一个二阶集合(二阶元组,tuple)
# 实例
data = cursor.fetchone()
print(data)
print(type(data))data = cursor.fetchall()
for rows in data:print(rows)print(type(rows))
6.事务的用法
通常,mysql事务用法用于有修改权限的用户。
在mysql中执行一次事务需要begin commit rollback 三种功能。
在pymysql接口中只需要commit
rollback
两种即可。并需要使用异常捕获机制完成。
- 执行案例
import pymysqldb = pymysql.connect(host='localhost',user='root',password='123456',database='dnf')
# 创建访问对象
cursor = db.cursor()
sql = "SELECT * FROM `key`"try:# 执行SQL语句cursor.execute(sql)# 向数据库提交db.commit()
except:# 发生错误时回滚db.rollback()
db.close()
7. 关闭mysql链接 close
语法
db.close()
代码上下文
import pymysqldb = pymysql.connect(host='localhost',user='root',password='123456',database='dnf')db.close()