【问题标题】:why cannot insert python variable into sql query?为什么不能将python变量插入sql查询?
【发布时间】:2022-01-25 18:19:47
【问题描述】:

我无法使用 python 变量将时间戳插入 mysql (v8.0.27) 数据库。 (注意我使用 pymysql 作为光标)。

以下代码按预期工作:

testQuery = f"""
      INSERT INTO test_table_2(time, id) VALUES ('2020-05-23 05:30:10', 4);
      """
cursor.execute(testQuery)

但是下面的代码不起作用:

time = '2020-05-23 05:30:10'
testQuery = f"""
      INSERT INTO test_table_2(time, id) VALUES ({time}, 4);
      """
cursor.execute(testQuery)

并给出以下错误

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 '05:30:10, 4)' at line 1")

(我知道使用 f-strings 对注入攻击不利,但目前我并不太关心这一点,因为我只是想让一些简单的工作。但是也欢迎任何改进建议。我已经尝试过使用存储过程和其他方式的其他更复杂的方法,但这也不起作用。如果有人可以帮助解决这个问题的存储过程版本,请在此处发帖:cannot insert datetime field with stored procedure into mysql database)

该表是使用以下架构创建的:

CREATE TABLE IF NOT EXISTS test_table_2 (
          id INT, 
          time TIMESTAMP,
          PRIMARY KEY (time)
          );

【问题讨论】:

  • 使用print(testQuery),你会发现问题。

标签: python mysql pymysql


【解决方案1】:

您忘记在 {time} 周围加上引号,就像您使用硬编码时间戳所做的那样。

但不要使用字符串替换,使用带参数的预处理语句。

time = '2020-05-23 05:30:10'
testQuery = f"""
      INSERT INTO test_table_2(time, id) VALUES (%s, 4);
      """
cursor.execute(testQuery, (time,))

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 2019-05-22
    • 2020-08-09
    • 2018-07-06
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多