Python数据库编程

我们用如下所示的数据库来演示在Python中如何访问MySQL数据库。

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

在Python 3中,我们通常使用纯Python的三方库PyMySQL来访问MySQL数据库,它应该是目前Python操作MySQL数据库最好的选择。

  1. 安装PyMySQL。

    1. pip install pymysql
  2. 添加一个部门。

    ```Python import pymysql

def main(): no = int(input(‘编号: ‘)) name = input(‘名字: ‘) loc = input(‘所在地: ‘)

  1. # 1. 创建数据库连接对象
  2. con = pymysql.connect(host='localhost', port=3306,
  3. database='hrs', charset='utf8',
  4. user='yourname', password='yourpass')
  5. try:
  6. # 2. 通过连接对象获取游标
  7. with con.cursor() as cursor:
  8. # 3. 通过游标执行SQL并获得执行结果
  9. result = cursor.execute(
  10. 'insert into tb_dept values (%s, %s, %s)',
  11. (no, name, loc)
  12. )
  13. if result == 1:
  14. print('添加成功!')
  15. # 4. 操作成功提交事务
  16. con.commit()
  17. finally:
  18. # 5. 关闭连接释放资源
  19. con.close()

if name == ‘main‘: main()

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

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

  1. 更新一个部门。

    ```Python import pymysql

def main(): no = int(input(‘编号: ‘)) name = input(‘名字: ‘) loc = input(‘所在地: ‘) con = pymysql.connect(host=’localhost’, port=3306, database=’hrs’, charset=’utf8’, user=’yourname’, password=’yourpass’, autocommit=True) try: with con.cursor() as cursor: result = cursor.execute( ‘update tb_dept set dname=%s, dloc=%s where dno=%s’, (name, loc, no) ) if result == 1: print(‘更新成功!’) finally: con.close()

if name == ‘main‘: main()

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

    ```Python import pymysql from pymysql.cursors import DictCursor

class Emp(object):

  1. def __init__(self, no, name, job, sal):
  2. self.no = no
  3. self.name = name
  4. self.job = job
  5. self.sal = sal
  6. def __str__(self):
  7. return f'\n编号:{self.no}\n姓名:{self.name}\n职位:{self.job}\n月薪:{self.sal}\n'

def main(): page = int(input(‘页码: ‘)) size = int(input(‘大小: ‘)) con = pymysql.connect(host=’localhost’, port=3306, database=’hrs’, charset=’utf8’, user=’yourname’, password=’yourpass’) try: with con.cursor() as cursor: cursor.execute( ‘select eno as no, ename as name, job, sal from tb_emp limit %s,%s’, ((page - 1) size, size) ) for emp_tuple in cursor.fetchall(): emp = Emp(emp_tuple) print(emp) finally: con.close()

if name == ‘main‘: main() ```