初始化包
安装pymysql模块
cmd安装
pip3 install pymysql
# 验证:python进入窗口输入 -> import pymysql 不报错即可
手动安装
File=>settings
创建表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for test_order
-- ----------------------------
DROP TABLE IF EXISTS `test_order`;
CREATE TABLE `test_order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of test_order
-- ----------------------------
INSERT INTO `test_order` VALUES (2, 'Lucy', 12);
INSERT INTO `test_order` VALUES (3, 'Lucy', 12);
SET FOREIGN_KEY_CHECKS = 1;
Demo
# 导入pymysql包
import pymysql
# 创建连接对象
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", database="seata",
charset="utf8")
# 获取游标对象
cs = conn.cursor()
print("查询表数据")
# pymysql完成数据的查询条件
sql = "select * from test_order;"
cs.execute(sql)
# for循环来显示数据
cs.execute(sql)
content = cs.fetchall()
for i in content:
print(i)
print("修改数据")
# 修改数据
sql = "update test_order set name='Lilo' where id=1;"
cs.execute(sql)
# 提交操作
conn.commit()
print("新增数据")
# 增加数据:pycharm默认是开启事务的,此时客户端访问students表还是原来的数据,因此需要提交事务
sql = "insert into test_order(name,age) values('Lucy',12);"
cs.execute(sql)
# 提交操作
conn.commit()
print("再次查询表数据")
# pymysql完成数据的查询条件
sql = "select * from test_order;"
cs.execute(sql)
# for循环来显示数据
cs.execute(sql)
content = cs.fetchall()
for i in content:
print(i)
print("删除查询表数据")
# 删除数据
sql = "delete from test_order where id = 1;"
cs.execute(sql)
# 提交操作
conn.commit()
# 关闭游标和连接
cs.close()
conn.close()
Q&A
1. pip安装三方库不成功
提示:WARNING: You are using pip version 20.2.3, however version 20.2.4 is available.
原因:pip版本过低导致安装第三方库失败
## 直接输入下面命令解决
python -m pip install --upgrade pip