我正试图通过一个python脚本运行my SQL查询,并不断在我的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注入风险:
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/