今天来介绍python链接MySQL的操作流程。

pymysql的安装与使用

  • ​​pymysql 的安装​​
  • ​​pymysql 的使用​​
  • ​​创建数据库链接​​
  • ​​sql语句操作​​
  • ​​fetchall():查询全部语句​​
  • ​​fetchone():查询单条语句​​
  • ​​fetchmany():查询多条语句​​
  • ​​关闭数据库链接​​

pymysql 的安装

这里推荐直接 pip方法安装, 方便快捷,省时省事!

pip instal  pymysql

pymysql 的使用

链接数据库操作,无非就是以下这几个步骤;
1.创建数据库链接;
2.进行sql语句操作;
3.关闭数据库链接;

所以,我们接下来,就看看,如何连接数据库,如何进行操作。

创建数据库链接

import pymysql

#链接数据库
connection = pymysql.connect(
host = "localhost", #填写数据库的主机IP地址
user = 'root', #数据库用户名
password = '123456', #数据库密码
port = '3306', #数据库端口号
database = 'test', #数据库的名称
)

sql语句操作

我们如何进行sql语句操作呢?
cursor方法:

cursor提供了三种方法,分别是 fetchone,fetchmany,fetchall。
①fetchone() :用于查询单条数据,返回元组,没有返回None;
②fetchmany(size) : 接受size行返回结果。如果size大于返回的结果行数量,怎返回cursor.arraysize条数据;
③fetchall():用于查询全部数据。

commit() 提交事务

connection.commit():将修改的数据提交到数据库;

fetchall():查询全部语句

#创建sql语句
sql = "select * from base_role where role_name = '管理员'"
#执行sql语句
try:
cursor.execute(sql)
results = cursor.fetchall() #全部查询
for i in results:
role_id = i['id']
print(role_id)
except Exception as e:
print("Unable to fetch data!", format(e))

fetchone():查询单条语句

#创建sql语句并执行
sql = "select * from base_role where role_name = '系统管理员'"
cursor.execute(sql)

#查询单条数据
result = cursor.fetchone()
print(result)

fetchmany():查询多条语句

#创建sql语句并执行
sql = "select * from base_role"
cursor.execute(sql)

#查询多条数据
results = cursor.fetchmany(5) # 获取5条数据
print(type(results))
for res in results:
print(res)

关闭数据库链接

# 创建sql语句操作_更新
updata = "updata base_role set role_name = '系统管理员' where role_code = 3 "
cursor.execute(updata)

#查询单条数据
sql = "select * from base_role where role_name = '系统管理员'"
cursor.execute(sql)
#执行sql语句
result = cursor.fetchone()
print(result)

#提交sql语句
connection.commit()
#关闭数据库链接
connection.close()