【发布时间】: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),你会发现问题。