我正在尝试通过 python 脚本运行 MySQL 查询,但在我的 SQL 语法中不断出现错误,从我可以看到查询设置正确。有人可以给我第二眼吗?
conn = mysql.connector.connect(**config)
connect = conn.cursor()
query = u'INSERT INTO page_load_times (self, object_id, page_header, elapsed_time, date_run) ' \
'VALUES ({}, {}, {}, {}, {})'.format(self, self.object_id, self.page_header, t.interval, timestamp)
connect.execute(query)
conn.commit()
conn.close()
我得到的错误如下:
ProgrammingError: 1064 (42000): 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 '13:56:17.491000)' at line 1
最佳答案
不要通过字符串格式传递查询参数。
让 mysql 客户端通过将参数传递到 execute()
的第二个参数中的查询来完成这项工作。除了没有引号和数据类型转换的问题外,您还可以避免 sql 注入(inject)风险:
query = """INSERT INTO
page_load_times
(self, object_id, page_header, elapsed_time, date_run)
VALUES
(%(self)s, %(object_id)s, %(page_header)s, %(interval)s, %(timestamp)s)"""
params = {'self': self,
'object_id': self.object_id,
'page_header': self.page_header,
'interval': t.interval,
'timestamp': timestamp}
connect.execute(query, params)
关于python - SQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942940/