SQL语法中的错误

时间:2014-07-24 20:02:20

标签: python mysql sql python-2.7 mysql-python

我试图通过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

1 个答案:

答案 0 :(得分:5)

不要通过字符串格式传递查询参数。

让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)