Pyhton中防止SQL注入的方法
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))
注意,上面的SQL字符串與后面的tuple之間的分隔符是逗號,平時拼寫SQL用的是%。
如果按照以下寫法,是容易產(chǎn)生SQL注入的:
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""" % (max_price,))
這個和PHP里的PDO是類似的,原理同MySQL Prepared Statements。
Python
Using the Python DB API, don't do this:
# Do NOT do it this way.
cmd = "update people set name='%s' where id='%s'" % (name, id) curs.execute(cmd)
Instead, do this:
cmd = "update people set name=%s where id=%s" curs.execute(cmd, (name, id))
Note that the placeholder syntax depends on the database you are using.
The values for the most common databases are:
>>> import MySQLdb; print MySQLdb.paramstyle format >>> import psycopg2; print psycopg2.paramstyle pyformat >>> import sqlite3; print sqlite3.paramstyle qmark
So if you are using MySQL or PostgreSQL, use %s (even for numbers and other non-string values!) and if you are using SQLite use ?
相關(guān)文章
python3.5 + PyQt5 +Eric6 實現(xiàn)的一個計算器代碼
這篇文章主要介紹了python3.5 + PyQt5 +Eric6 實現(xiàn)的一個計算器代碼,在windows7 32位系統(tǒng)可以完美運行 計算器,有興趣的可以了解一下。2017-03-03python用pip install時安裝失敗的一系列問題及解決方法
這篇文章主要介紹了python用pip install時安裝失敗的一系列問題,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02python中hasattr()、getattr()、setattr()函數(shù)的使用
這篇文章主要介紹了python中hasattr()、getattr()、setattr()函數(shù)的使用方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08Python 循環(huán)語句之 while,for語句詳解
Python中有兩種循環(huán),分別為:for循環(huán)和while循環(huán)。 for循環(huán)可以遍歷任何序列的項目,如一個列表或者一個字符串。while 語句用于循環(huán)執(zhí)行程序,即在某條件下,循環(huán)執(zhí)行某段程序,以處理需要重復(fù)處理的相同任務(wù)。2018-04-04