辣椒鲨鱼面 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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果