改进SQL INSERT查询以避免sql注入

时间:2018-03-09 12:18:17

标签: python mysql sql sql-injection sql-insert

我使用pymyql / mysql-connector将消息写入mysql数据库。消息在回调(paho.mqtt回调)上从mqtt broker处理。我有4个不同的表,根据消息类型,我将消息插入数据库。我已经编写了插入查询,如下所示。这种写入方式似乎导致了sql注入。任何建议如何改进插入查询语句?

# callback attached to paho.mqtt.client    
def on_message(self, client, userdata, msg):

    if  msg.topic.startswith("topic1/"):
        self.bulkpayload += "(" + msg.payload.decode("utf-8") + "," + datetime + "),"
    elif msg.topic.startswith("topic2/"):
        self.insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
    elif msg.topic.startswith("topic3/")   
        self.insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
    elif msg.topic.startswith("messages"):
        self.insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "',"  + msg.payload.decode("utf-8") + "," + datetime + ");"
    else:
    return  # do not store in DB

    cursor.execute(self.insertStatement)
    cursor.commit()

1 个答案:

答案 0 :(得分:3)

使您的查询使用参数。注射的机会要少得多:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

信用(以及更多信息):How to use variables in SQL statement in Python?

另外,Dan Bracuk是正确的 - 如果你还没有

,请确保在执行SQL之前验证你的参数