Dar*_*pto 1 python mysql sql mysql-python python-2.7
我试图通过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()
Run Code Online (Sandbox Code Playgroud)
我得到的错误如下:
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
Run Code Online (Sandbox Code Playgroud)
不要通过字符串格式传递查询参数.
让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)
Run Code Online (Sandbox Code Playgroud)