Improve SQL INSERT query to avoid sql injections

[亡魂溺海] 提交于 2020-11-29 19:05:17

问题


I am using pymyql/mysql-connector to write the messages to mysql database. The messages are processed on callback (paho.mqtt callback) from mqtt broker.I have 4 different tables and based on the message type, I am inserting messages into database. I have written the insert queries as below. this way of writing leads to sql injections it seems.Any suggestions how can I improve the insert query statements?

# 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:


Make your query use parameters. Much less chance of injection:

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

credit (and more info) here: How to use variables in SQL statement in Python?

Also, Dan Bracuk is correct - make sure you validate your params before executing the SQL if you aren't already



来源:https://stackoverflow.com/questions/49193680/improve-sql-insert-query-to-avoid-sql-injections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!