pycharm操作MYSQL
1.往mysql里面写数据
import pymysql
no = int(input('部门编号:'))
name = input('部门名称:')
location = input('部门所在地:')
conn = pymysql.connect(host='localhost', port=3307,
user='guest', password='Guest.618',
database='hrs', charset='utf8mb4'
)
try:
cursor = conn.cursor()
affected_rows = cursor.execute('insert into tb_dept(dno, dname, dloc) values(%s,%s,%s)',
(no, name, location)
)
if affected_rows == 1:
print("数据添加成功!")
conn.commit()
except pymysql.MySQLError as err:
print(err)
conn.rollback()
finally:
conn.close()
2. 在pycharm中删除操作
affected_rows1 = cursor.execute(
'delete from tb_dept where dno = %s', (no,)
)
3.在pycharm中修改操作
affected_rows2 = cursor.execute(
'update tb_dept set dname = %s,dloc = %s where dno = %s,(name,location,no)
)
4.查询数据
import pymysql
conn = pymysql.connect(host='localhost', port=3307,
user='guest', password='Guest.618',
database='hrs', charset='utf8mb4'
)
try:
cursor = conn.cursor()
affected_rows = cursor.execute(
'''select dno
,dname
,dloc
from tb_dept'''
)
data = cursor.fetchone()
while data:
print(data)
data = cursor.fetchone()
except pymysql.MySQLError as err:
print(err)
finally:
conn.close()
5.将数据库的二维表导出到excle
import pymysql
import openpyxl
from openpyxl.worksheet.worksheet import Worksheet
wb = openpyxl.Workbook()
sheet1 = wb.active
sheet1.title = '部门表'
sheet1.append(('部门编号', '部门名称', '所在地'))
sheet2 = wb.create_sheet('员工表')
sheet2.append(('工号', '姓名', '职位', '主管', '月薪', '补贴', '所属部门'))
conn = pymysql.connect(host='localhost', port=3307,
user='guest', password='Guest.618',
database='hrs', charset='utf8mb4'
)
try:
cursor = conn.cursor()
affected_rows = cursor.execute(
'''select dno
,dname
,dloc
from tb_dept'''
)
while data := cursor.fetchone():
sheet1.append(data)
cursor.execute(
'''select t1.eno
,t1.ename
,t1.job
,t2.ename
,t1.sal
,t1.comm
,dname
from tb_emp as t1 left join tb_emp as t2
on t1.mgr=t2.eno inner join tb_dept as t3
on t1.dno = t3.dno'''
)
while data := cursor.fetchone():
sheet2.append(data)
except pymysql.MySQLError as err:
print(err)
finally:
wb.save('人力资源管理.xlsx')
conn.close()