使用Navicat插入
新建包含两个字段,分别是id(自增主键),name(姓名)的数据表
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` `varchar`(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
在Navicat中使用原生sql直接插入100%
insert into student(name) VALUES ('100%')
返回
Affected rows: 1, Time: 0.001000s
数据库查看,确实插入了
使用peewee模块链接数据库
import peewee
db = peewee.MySQLDatabase(
host="localhost",
port=3306,
user="root",
password="123456",
database="demo",
)
db.execute_sql("insert into student(name) VALUES ('100%')")
db.close()
报错:
TypeError: not enough arguments for format string
可以看出%
被格式化字符占用了
解决方法:
1、将sql语句改为
db.execute_sql("insert into student(name) VALUES ('100%%')")
将%
转义之后就可以正常插入了, 使用%s
格式化和 format
格式化效果是一样的
这样有个不好的地方,每次传递的参数都需要做修改
2、 execute_sql
还有一个参数params
,接收一个元组
db.execute_sql("insert into student(name) VALUES (%s)", ("1000%",))
这样也能执行成功,推荐使用此方法,而且还能防止sql注入攻击
tips
: peewee的数据库链接使用完后需要手动关闭下,加一个close
,不然会一直占用连接
可参考: python 防止sql注入字符串拼接的正确用法