如何在SQL语句中传入正确的数据类型?——python3.6, pymysql

很奇怪的一个问题

我想用python3.6中的pymysql包将数据传入到MySQL中, 数据库中的表的类型分别是(简略):

nick_name VARCHAR(...),
content VARCHAR(...),
time DATETIME,
num_like INT,
num_forward INT,
num_comment INT,

于是有了如下语句:

sql_insert = "INSERT INTO `post` (`nick_name`, content`, `time`, `num_like`, `num_forward`, `num_comment`) VALUES (%s, %s, %s, %d, %d, %d)"
cursor.execute(sql_insert, ('Jack', 'Wow!', '2017-11-17 11:20', 20, 30, 30))


当然,在编译过程中遇到了如下错误:

TypeError: %d format: a number is required, not str

于是我谷歌了一番,在stackoverflow上,有个大神给出了答案

The format string is not really a normal Python format string. You must always use %s for all fields.

意思是在SQL里,不能用%d,要换成%s.

后来,我在pymysql文档中也找到了相似的解答。于是,我将代码修改成:

sql_insert = "INSERT INTO `post` (`nick_name`, content`, `time`, `num_like`, `num_forward`, `num_comment`) VALUES (%s. %s, %s, %s, %s, %s)"

但是,又报了如下错误:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`, `time`, `num_like`, `num_forward`, `num_comment`) \n VALUES ('Jack'. 'W' at line 2")

这一次,我找不到答案了。因为好像很少有人到这一步还出错的……

求各位大神解答……

sql_insert = "INSERT INTO post (nick_name, content,time,num_like,num_forward,num_comment`) VALUES (%s, %s, %s, %s, %s, %s)"
全都使用%s,而且第一个%s后面你不是写的逗号

TypeError: %d format: a number is required, not str

这句的意思是,%d 占位符,需要一个数字,而不是字符串。

如果你用不了%s或者有问题,可以试一下,先用下面这种方式:

sql_insert = "INSERT INTO post (nick_name, content,time,num_like,num_forward,num_comment) VALUES ("+xx+", "+xx+", "+xx+", "+xx+","+xx+","+xx+")

看看这种方式.

你的SQL报错,显示成下面这样了:看不清具体错误

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to

把表字段全改成varchar,写入完再改回来。