‘’‘1、 功能描述
1 创建一个部门表(department),包含字段id,name
2创建一个员工表(employees),包含字段id,name,birthday,gender,salary,dep_id 使用外键引用到部门表中的id字段,并且添加一个普通索引到name字段
3 在部门表中添加三条记录 id:1 name:技术部,id:2 name:财务部,id:3 name:市场部
4 在员工表里添加六条记录,
id:1 name:’张三’ birthday:”2010-11-10” gender:’男’ salary:”5000.00” dep_id:1
id:2 name:’李四’ birthday:”2012-11-10” gender:’女’ salary:”8000.00” dep_id:1
id:3 name:’王五’ birthday:”2014-11-10” gender:’男’ salary:”15000.00” dep_id:2
id:4 name:’小明’ birthday:”2013-11-10” gender:’女’ salary:”6000.00” dep_id:2
id:5 name:’小李’ birthday:”2015-11-10” gender:’女’ salary:”7000.00” dep_id:2
id:6 name:’小刘’ birthday:”2008-11-10” gender:’男’ salary:”3000.00” dep_id:3
‘’’
import pymysql
import re
con=pymysql.connect(
host=‘localhost’,
port= 3306,
user= ‘root’,
password=‘123456’,
database=‘ccc’)
cur=con.cursor()#链接数据库
“”“5 使用pymysql模块来查询每个部门的平均工资
如 技术部 5000
市场部 1000
财务部 0"”"
#qq=‘select department.name,avg(employees.salary) from employees inner join department on department.id=employees.dep_id group by employees.dep_id’
#cur.execute(qq)#执行语句
‘’‘6 修改张三的名字为张五’’’
cur.execute(‘update employees set name=“张五” where name=“张三”’)#改名
con.commit()
dd=cur.fetchall()#获取查询结果
print(dd)#输出查询结果
‘’‘7 删除部门名字为”市场部”的所有员工’’’
#cur.execute(‘delete from employees where dep_id=3’)
‘’‘8 查询技术部工资最高的人’’’
#cur.execute(‘select name,salary from employees where dep_id=2 order by salary desc limit 1’)
‘’‘9 查询部门内有员工的部门信息(用子查询实现)’’’
‘’‘10 查询以‘小’开头的名字为一个字员工’’’
cur.execute(‘select name from employees’)
a=cur.fetchall()
z=[]
for i in range(len(a)):
z.append(a[i][0])#将所有姓名加进一个列表中
for q in z:#获取每一个名字
m=re.search(‘小+\w’,q)#利用正则匹配查询结果
if m !=None:#如果有值时输出,防止报错
print(m.group())#输出
‘’‘11查询出生日期在2008-11-10到2012-11-10的员工’’’
cur.execute(‘select name from employees where birthday between 20081110 and 20121110’)#按生日查询
a=cur.fetchall()#获取查询结果
print(a)#输出查询结果
cur.close()
con.close()