辣椒鲨鱼面 2017-11-17 14:56 采纳率: 0%
浏览 4512

如何在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")

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

求各位大神解答……

  • 写回答

3条回答

  • doggy_coder 2017-11-17 15:39
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题