初始化包

连接mysql,需要安装包

安装pymysql模块

cmd安装

  1. pip3 install pymysql
  2. # 验证:python进入窗口输入 -> import pymysql 不报错即可

手动安装

File=>settings
image.png

image.png

创建表

  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS = 0;
  3. -- ----------------------------
  4. -- Table structure for test_order
  5. -- ----------------------------
  6. DROP TABLE IF EXISTS `test_order`;
  7. CREATE TABLE `test_order` (
  8. `id` int(11) NOT NULL AUTO_INCREMENT,
  9. `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  10. `age` int(11) NULL DEFAULT NULL,
  11. PRIMARY KEY (`id`) USING BTREE
  12. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
  13. -- ----------------------------
  14. -- Records of test_order
  15. -- ----------------------------
  16. INSERT INTO `test_order` VALUES (2, 'Lucy', 12);
  17. INSERT INTO `test_order` VALUES (3, 'Lucy', 12);
  18. SET FOREIGN_KEY_CHECKS = 1;

Demo

  1. # 导入pymysql包
  2. import pymysql
  3. # 创建连接对象
  4. conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", database="seata",
  5. charset="utf8")
  6. # 获取游标对象
  7. cs = conn.cursor()
  8. print("查询表数据")
  9. # pymysql完成数据的查询条件
  10. sql = "select * from test_order;"
  11. cs.execute(sql)
  12. # for循环来显示数据
  13. cs.execute(sql)
  14. content = cs.fetchall()
  15. for i in content:
  16. print(i)
  17. print("修改数据")
  18. # 修改数据
  19. sql = "update test_order set name='Lilo' where id=1;"
  20. cs.execute(sql)
  21. # 提交操作
  22. conn.commit()
  23. print("新增数据")
  24. # 增加数据:pycharm默认是开启事务的,此时客户端访问students表还是原来的数据,因此需要提交事务
  25. sql = "insert into test_order(name,age) values('Lucy',12);"
  26. cs.execute(sql)
  27. # 提交操作
  28. conn.commit()
  29. print("再次查询表数据")
  30. # pymysql完成数据的查询条件
  31. sql = "select * from test_order;"
  32. cs.execute(sql)
  33. # for循环来显示数据
  34. cs.execute(sql)
  35. content = cs.fetchall()
  36. for i in content:
  37. print(i)
  38. print("删除查询表数据")
  39. # 删除数据
  40. sql = "delete from test_order where id = 1;"
  41. cs.execute(sql)
  42. # 提交操作
  43. conn.commit()
  44. # 关闭游标和连接
  45. cs.close()
  46. conn.close()

Q&A

1. pip安装三方库不成功

提示:WARNING: You are using pip version 20.2.3, however version 20.2.4 is available.

原因:pip版本过低导致安装第三方库失败
image.png

  1. ## 直接输入下面命令解决
  2. python -m pip install --upgrade pip