当前位置:   article > 正文

Python操作MySQL

Python操作MySQL

1.连接数据库

安装pymysql模块
pip install pymysql

  1. import pymysql
  2. # 连接mysql
  3. # 参数1:表示主机或ip地址
  4. # 参数2:表述端口号
  5. # 参数3:表示mysql的用户名
  6. # 参数4:表示mysql的密码
  7. # 参数5:表示mysql的数据库名
  8. conn = pymysql.connect(host='127.0.0.1',port=3306,user='root', password='root', database='mydb2')
  9. # 创建游标对象: 可以执行sql语句
  10. cursor = conn.cursor()
  11. # sql语句
  12. sql = 'show tables'
  13. # 执行sql语句
  14. cursor.execute(sql)
  15. res = cursor.fetchall()
  16. print(res)
  17. # 关闭游标对象
  18. cursor.close()
  19. # 关闭mysql的连接
  20. conn.close()

2.增删改mysql数据

  1. import pymysql
  2. db = pymysql.connect(host='127.0.0.1', port=3306, user="root", password="root", database="数据库名")
  3. '''
  4. cursor = db.cursor()
  5. cursor.close()
  6. '''
  7. #使用with关键词可以不用手动关闭游标,会自动关闭
  8. with db.cursor() as cur:
  9. # 增
  10. # sql = "insert into stu values(1005,'美女')"
  11. # 删
  12. # sql = "delete from stu where stuid = 1001"
  13. # 改
  14. sql = "update stu set stuname = '小丽' where stuid = 1002"
  15. try:
  16. cur.execute(sql)
  17. # 成功后提交事务
  18. db.commit()
  19. except:
  20. # 失败后 回滚
  21. db.rollback()
  22. db.close()

3.查询数据

  1. import pymysql
  2. db = pymysql.connect(host='127.0.0.1', port=3306, user="root", password="root", database="数据库名")
  3. with db.cursor() as cur:
  4. try:
  5. sql = "select * from student"
  6. cur.execute(sql)
  7. # 获取查询的结果
  8. '''
  9. fetchall() 获取所有数据
  10. fetchone() 获取一条数据 调用一次输出一条数据
  11. fetchmany(n) 获取n条数据
  12. '''
  13. # print(cur.fetchall())
  14. # print(cur.fetchone())
  15. # print(cur.fetchone())
  16. # print(cur.fetchone())
  17. print(cur.fetchmany(4)) # 获取4条数据
  18. print(cur.fetchmany(14)) # 获取14条数据
  19. except:
  20. print("查询失败")
  21. db.close()

4.总结

1)基本步骤:

(1)引入第三方模块:import pymysql

(2)连接数据库:db = pymysql.connect(host='127.0.0.1', port=3306, user='用户名', password='数据库密码', database='数据库名')

(3)创建游标:cursor = db.cursor()

(4)准备sql语句对数据库进行操作(用try...except..语句捕获和抛出异常,如果出现错误对数据库进行回滚)

(5)关闭游标(如果使用with...as就不用关闭):cursor.close()

(6)关闭数据库:db.close()

2)增删改操作都需要对数据进行提交操作commit(),而查询操作不需要进行提交操作

5.练习

1)创建表格, 并添加数据 

  1. create table tb_dept
  2. (
  3. dno int not null comment '编号',
  4. dname varchar(10) not null comment '名称',
  5. dloc varchar(20) not null comment '所在地',
  6. primary key (dno)
  7. );
  8. insert into tb_dept values
  9. (10, '会计部', '北京'),
  10. (20, '研发部', '成都'),
  11. (30, '销售部', '重庆'),
  12. (40, '运维部', '深圳');
  13. create table tb_emp
  14. (
  15. eno int not null comment '员工编号',
  16. ename varchar(20) not null comment '员工姓名',
  17. job varchar(20) not null comment '员工职位',
  18. mgr int comment '主管编号',
  19. sal int not null comment '员工月薪',
  20. comm int comment '每月补贴',
  21. dno int comment '所在部门编号',
  22. primary key (eno)
  23. );
  24. alter table tb_emp add constraint fk_emp_dno foreign key (dno) references tb_dept (dno);
  25. insert into tb_emp values
  26. (7800, '张三丰', '总裁', null, 9000, 1200, 20),
  27. (2056, '乔峰', '分析师', 7800, 5000, 1500, 20),
  28. (3088, '李莫愁', '设计师', 2056, 3500, 800, 20),
  29. (3211, '张无忌', '程序员', 2056, 3200, null, 20),
  30. (3233, '丘处机', '程序员', 2056, 3400, null, 20),
  31. (3251, '张翠山', '程序员', 2056, 4000, null, 20),
  32. (5566, '宋远桥', '会计师', 7800, 4000, 1000, 10),
  33. (5234, '郭靖', '出纳', 5566, 2000, null, 10),
  34. (3344, '黄蓉', '销售主管', 7800, 3000, 800, 30),
  35. (1359, '胡一刀', '销售员', 3344, 1800, 200, 30),
  36. (4466, '苗人凤', '销售员', 3344, 2500, null, 30),
  37. (3244, '欧阳锋', '程序员', 3088, 3200, null, 20),
  38. (3577, '杨过', '会计', 5566, 2200, null, 10),
  39. (3588, '朱九真', '会计', 5566, 2500, null, 10);

2)添加一个部门

  1. import pymysql
  2. def main():
  3. no = int(input('编号: '))
  4. name = input('名字: ')
  5. loc = input('所在地: ')
  6. # 1. 创建数据库连接对象
  7. con = pymysql.connect(host='localhost', port=3306,database='hrs', charset='utf8',user='yourname', password='yourpass')
  8. try:
  9. # 2. 通过连接对象获取游标
  10. with con.cursor() as cursor:
  11. # 3. 通过游标执行SQL并获得执行结果
  12. result = cursor.execute(
  13. 'insert into tb_dept values (%s, %s, %s)',
  14. (no, name, loc)
  15. )
  16. if result == 1:
  17. print('添加成功!')
  18. # 4. 操作成功提交事务
  19. con.commit()
  20. except:
  21. # 回滚
  22. con.rollback()
  23. finally:
  24. # 5. 关闭连接释放资源
  25. con.close()
  26. if __name__ == '__main__':
  27. main()

3)删除一个部门

  1. import pymysql
  2. def main():
  3. no = int(input('编号: '))
  4. con = pymysql.connect(host='localhost',port=3306,database='hrs',charset='utf8',user='yourname', password='yourpass',autocommit=True)
  5. try:
  6. with con.cursor() as cursor:
  7. result = cursor.execute(
  8. 'delete from tb_dept where dno=%s',
  9. (no, )
  10. )
  11. if result == 1:
  12. print('删除成功!')
  13. finally:
  14. con.close()
  15. if __name__ == '__main__':
  16. main()

说明:如果不希望每次SQL操作之后手动提交或回滚事务,可以像上面的代码那样,在创建连接的时候多加一个名为autocommit的参数并将它的值设置为True,表示每次执行SQL之后自动提交。如果程序中不需要使用事务环境也不希望手动的提交或回滚就可以这么做。

4)更新一个部门

  1. import pymysql
  2. def main():
  3. no = int(input('编号: '))
  4. name = input('名字: ')
  5. loc = input('所在地: ')
  6. con = pymysql.connect(host='localhost', port=3306,database='hrs', charset='utf8',user='yourname', password='yourpass',autocommit=True)
  7. try:
  8. with con.cursor() as cursor:
  9. result = cursor.execute(
  10. 'update tb_dept set dname=%s, dloc=%s where dno=%s',
  11. (name, loc, no)
  12. )
  13. if result == 1:
  14. print('更新成功!')
  15. finally:
  16. con.close()
  17. if __name__ == '__main__':
  18. main()

5)查询所有部门

  1. import pymysql
  2. from pymysql.cursors import DictCursor
  3. def main():
  4. con = pymysql.connect(host='localhost', port=3306,database='hrs', charset='utf8',user='yourname', password='yourpass')
  5. try:
  6. with con.cursor(cursor=DictCursor) as cursor:
  7. cursor.execute('select dno as no, dname as name, dloc as loc from tb_dept')
  8. results = cursor.fetchall()
  9. print(results)
  10. print('编号\t名称\t\t所在地')
  11. for dept in results:
  12. print(dept['no'], end='\t')
  13. print(dept['name'], end='\t')
  14. print(dept['loc'])
  15. finally:
  16. con.close()
  17. if __name__ == '__main__':
  18. main()

6)分页查询员工信息

  1. import pymysql
  2. class Emp(object):
  3. def __init__(self, no, name, job, sal):
  4. self.no = no
  5. self.name = name
  6. self.job = job
  7. self.sal = sal
  8. def __str__(self):
  9. return f'\n编号:{self.no}\n姓名:{self.name}\n职位:{self.job}\n月薪:{self.sal}\n'
  10. def main():
  11. page = int(input('页码: '))
  12. size = int(input('大小: '))
  13. con = pymysql.connect(host='localhost', port=3306,database='hrs', charset='utf8',user='yourname', password='yourpass')
  14. try:
  15. with con.cursor() as cursor:
  16. cursor.execute(
  17. 'select eno, ename, job, sal from tb_emp limit %s,%s',
  18. ((page - 1) * size, size)
  19. )
  20. results = cursor.fetchall()
  21. for emp_tuple in results:
  22. emp = Emp(*emp_tuple)
  23. print(emp)
  24. finally:
  25. con.close()
  26. if __name__ == '__main__':
  27. main()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/634761
推荐阅读
相关标签
  

闽ICP备14008679号