【问题标题】:python sql insert statement inserting values with quotes in databasepython sql insert语句在数据库中插入带引号的值
【发布时间】:2020-04-28 01:03:24
【问题描述】:

我正在尝试使用以下语句在 python 中将数据插入 Mysql

cursor.execute('INSERT INTO batch_details (batch_id,plant_id,product_code) VALUES ("%s","%s","%s")', (id, plantcode, pcode))

这里 id ="75", plantcode="2", pcode="FG"

但是我在数据库中的值是用单引号插入到 mysql 数据库中的,即 '75','2','FG'

我不明白为什么用单引号插入这些值。 sql查询的语法好像是对的。

【问题讨论】:

  • 你试过... VALUES (%s, %s, %s) ...吗?
  • @Matthias 是的,我试过了,我现在得到了正确的输出。

标签: python mysql sql pymysql


【解决方案1】:

%s 表示您提供的值将被解释为字符串。对于您想要成为整数的那些,请尝试使用 %d 代替。如果您希望 SQL 将值解释为数字而不是字符串,您可能还需要去掉 VALUES 列表中 %d 部分周围的引号字符。

另外,当不同的程序或库打印一个字符串时,有些会用单引号字符打印,有些会用双引号字符打印。无论哪种方式,它仍然是数据库中的一个字符串,只是以不同的方式打印到屏幕上。

【讨论】:

    【解决方案2】:

    您是否确保首先将其转换为准备好的语句?请参阅文档示例here -

    cursor = cnx.cursor(prepared=True)
    stmt = "SELECT fullname FROM employees WHERE id = %s" # (1)
    cursor.execute(stmt, (5,))
    

    否则,如果你只想做直接的字符串操作,你应该这样做

    query = 'INSERT INTO batch_details (batch_id,plant_id,product_code) VALUES ("%s","%s","%s")'%(id, plantcode, pcode)
    cursor.execute(query)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      相关资源
      最近更新 更多