目录
一、mysql下载(最新8.0.28)
(1)地址:https://dev.mysql.com/downloads/mysql/
(2)在mysql中创建数据库studb,创建表t_student
T_Student_No | varchar(45) PK |
T_Student_Name | varchar(45) |
T_Student_Sex | varchar(45) |
T_Student_Age | varchar(45) |
T_Student_Dep | varchar(45) |
T_Student_memo | varchar(45) |
二、导入stu.csv数据
T_Student_No | T_Student_Name | T_Student_Sex | T_Student_Age | T_Student_Dep | T_Student_memo |
1122101 | 张三1 | 男 | 18 | 发电1 | 朱春强1 |
1122102 | 张三2 | 女 | 19 | 发电2 | 朱春强2 |
1122103 | 张三3 | 男 | 20 | 发电3 | 朱春强3 |
1122104 | 张三4 | 女 | 18 | 发电4 | 朱春强4 |
1122105 | 张三5 | 男 | 19 | 发电5 | 朱春强5 |
1122106 | 张三6 | 女 | 20 | 发电6 | 朱春强6 |
1122107 | 张三7 | 男 | 18 | 发电7 | 朱春强7 |
1122108 | 张三8 | 女 | 19 | 发电8 | 朱春强8 |
1122109 | 张三9 | 男 | 20 | 发电9 | 朱春强9 |
三、安装pymysql
(3)安装命令
pip install pymysql
(4)Connect()参数说明
pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(str): 连接编码
connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接
cursor对象支持的方法
execute(op) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
rowcount() 返回数据条数或影响行数
close() 关闭游标对象
四、程序代码
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 3 14:39:15 2022
@author: zhuchunqiang
"""
import pymysql
db = pymysql.connect(host='localhost',
user='root',
password='1234abcd!',
database='studb',
charset='utf8mb4',#mysql字符格式
cursorclass=pymysql.cursors.DictCursor)
try:
cursor = db.cursor();
sql = """SELECT T_Student_No,T_Student_Name,T_Student_Age,T_Student_Dep
FROM studb.t_student where T_Student_Age>18 and T_Student_Age<=20"""
cursor.execute(sql)
results = cursor.fetchall()
inum=0
print("学号,姓名,年龄,专业")
for row in results:
stu_No = row['T_Student_No']
stu_Name = row['T_Student_Name']
stu_Age = row['T_Student_Age']
stu_Dep = row['T_Student_Dep']
#打印结果
#print("学号:%s,姓名:%s,年龄:%s,专业:%s"\
inum += 1
print("%s,%s,%s,%s"\
%(stu_No,stu_Name,stu_Age,stu_Dep))
print("\n代码执行完毕...查询到%d条符合条件记录。" %(inum))
except pymysql.Error as err:
print(err)
finally:
cursor.close()
db.close()
五、运行结果
runfile('E:/PythonStudy/test/query_mysql.py', wdir='E:/PythonStudy/test')
学号,姓名,年龄,专业
1122102,张三2,19,发电2
1122103,张三3,20,发电3
1122105,张三5,19,发电5
1122106,张三6,20,发电6
1122108,张三8,19,发电8
1122109,张三9,20,发电9
代码执行完毕...查询到6条符合条件记录。