数据库 test ,boys 表当前数据
数据库 boys 表。在新建数据库 test 之后可以导入进去,运行SQL文件
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80015
Source Host : localhost:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 80015
File Encoding : 65001
Date: 09/01/2021 13:21:07
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for boys
-- ----------------------------
DROP TABLE IF EXISTS `boys`;
CREATE TABLE `boys` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`boyName` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`userCP` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of boys
-- ----------------------------
INSERT INTO `boys` VALUES (1, '欧阳嘉', 100);
INSERT INTO `boys` VALUES (2, '孔乐', 800);
INSERT INTO `boys` VALUES (3, '欧威', 50);
SET FOREIGN_KEY_CHECKS = 1;
导入 pymysql
import pymysql
创建初始化连接
conn = pymysql.connect(
host = '127.0.0.1',
# host 连接的mysql主机
user = 'root',
passwd = 'root',
port = 3306,
# port 端口号
database = 'test',
# database 数据库名称
charset='utf8'
# charset 采用的编码方式
)
创建游标
cursor = conn.cursor()
# 添加数据
cursor.execute("insert into boys(id,boyname,usercp) values ('%s','%s','%s');"
%(4,'hany','999')) # 执行 sql 语句
conn.commit()
# 删除数据
cursor.execute("delete from boys where id = %d"%(4)) # 执行 sql 语句
conn.commit()
# 修改数据
cursor.execute("update boys set boyname = '%s' where id = '%d'"
%('我最棒',3)) # 执行 sql 语句
conn.commit()
# 查数据
cursor.execute("select * from boys;") # 执行 sql 语句
print(cursor.fetchall())
关闭连接
cursor.close()
conn.close()
需要注意的点:
插入 insert 和 修改 update 语句,
需要 单引号括起来,才能进行正确的插入和修改数据
完整代码如下:
import pymysql
conn = pymysql.connect(
host = '127.0.0.1',
# host 连接的mysql主机
user = 'root',
passwd = 'root',
port = 3306,
# port 端口号
database = 'test',
# database 数据库名称
charset='utf8'
# charset 采用的编码方式
)
cursor = conn.cursor()
# 添加数据
cursor.execute("insert into boys(id,boyname,usercp) values ('%s','%s','%s');"
%(4,'hany','999')) # 执行 sql 语句
conn.commit()
# 删除数据
cursor.execute("delete from boys where id = %d"%(4)) # 执行 sql 语句
conn.commit()
# 修改数据
cursor.execute("update boys set boyname = '%s' where id = '%d'"
%('我最棒',3)) # 执行 sql 语句
conn.commit()
# 查数据
cursor.execute("select * from boys;") # 执行 sql 语句
print(cursor.fetchall())
cursor.close()
conn.close()
执行前:
执行后:
2021-01-09