Python Mysql
实验目的
掌握Python Mysql的增删改查等操作
知识点介绍
- 什么是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。
实验环境
Linux Ubuntu 16.04
Python 3.6
Ipython
PyCharm
实验内容
本实验共包含PyMySQL安装及测试连接、创建表、插入数据、查询数据、更新数据、删除数据等六部分内容
实验步骤
双击打开终端模拟器
1.首先,升级pip版本,然后使用pip命令安装PyMySQL
sudo pip install --upgrade pip
# 输入密码
sudo pip install PyMySQL
2.开启mysql服务
sudo service mysql start
3.开启mysql(密码:自定义的)
mysql -u root -p
4.创建并使用testdb数据库
create database testdb;
use testdb;
5.创建employee表,包含 (first_name varchar(20),last_name varchar(20),age int,sex char(5),income float)五个字段
create table employee(
first_name varchar(20),
last_name varchar(20),
age int,
sex char(5),
income float);
测试连接
6.使用vim编辑一个test.py文件,功能为测试是否可以连接上testdb数据库
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("select version()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
执行test.py文件
python3 test.py
创建表
7.使用vim编辑一个create.py文件,功能为创建一个employee表,如果该表已存在就删除重建
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("drop table if exists employee")
# 使用预处理语句创建表
sql = """create table employee(
first_name varchar(20) not null,
last_name varchar(20),
age int,
sex char(5),
income float )"""
print('create success!')
cursor.execute(sql)
# 关闭数据库连接
db.close()
执行create.py文件
python3 create.py
插入数据
8.使用vim编辑一个insert.py文件,功能为向employee表插入一行数据
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """insert into employee(first_name,
last_name,age,sex,income)
values ('TOM', 'Jack', 20, 'M', 2000)"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
# 关闭数据库连接
db.close()
print('insert success!')
执行insert.py文件
python3 insert.py
查询数据
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone():该方法获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行。
rowcount:这是一个只读属性,并返回执行execute()方法后影响的行数。
9.使用vim编辑一个fetch.py文件,功能为查询employee表中年龄大于18的数据
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "select * from employee \
where age > '%d'" % (18)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
first_name = row[0]
last_name = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(first_name, last_name, age, sex, income ))
except:
print ("Error: unable to fetch data")
# 关闭数据库连接
db.close()
执行fetch.py文件
python3 fetch.py
更新数据
10.使用vim编辑一个update.py文件,功能为将employ表中性别为M的数据,年龄+1
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "update employee set age = age + 1 where sex = '%c'" % ('M')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()
print('update success!')
执行update.py文件
python3 update.py
删除数据
11.使用vim编辑一个delete.py文件,功能为删除年龄大于20的数据
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","root","strongs","testdb" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 删除语句
sql = "delete from employee where age > '%d'" % (20)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 关闭连接
db.close()
print('delete success!')
执行delete.py文件
python3 delete.py