Pyhton中防止SQL注入的方法
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))
注意,上面的SQL字符串與后面的tuple之間的分隔符是逗號,平時(shí)拼寫SQL用的是%。
如果按照以下寫法,是容易產(chǎn)生SQL注入的:
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""" % (max_price,))
這個(gè)和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 實(shí)現(xiàn)的一個(gè)計(jì)算器代碼
這篇文章主要介紹了python3.5 + PyQt5 +Eric6 實(shí)現(xiàn)的一個(gè)計(jì)算器代碼,在windows7 32位系統(tǒng)可以完美運(yùn)行 計(jì)算器,有興趣的可以了解一下。2017-03-03python用pip install時(shí)安裝失敗的一系列問題及解決方法
這篇文章主要介紹了python用pip install時(shí)安裝失敗的一系列問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02python中hasattr()、getattr()、setattr()函數(shù)的使用
這篇文章主要介紹了python中hasattr()、getattr()、setattr()函數(shù)的使用方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08Python 循環(huán)語句之 while,for語句詳解
Python中有兩種循環(huán),分別為:for循環(huán)和while循環(huán)。 for循環(huán)可以遍歷任何序列的項(xiàng)目,如一個(gè)列表或者一個(gè)字符串。while 語句用于循環(huán)執(zhí)行程序,即在某條件下,循環(huán)執(zhí)行某段程序,以處理需要重復(fù)處理的相同任務(wù)。2018-04-04在Django的URLconf中使用多個(gè)視圖前綴的方法
這篇文章主要介紹了在Django的URLconf中使用多個(gè)視圖前綴的方法,Django是Python中最為著名的遵循MVC結(jié)構(gòu)的開發(fā)框架,需要的朋友可以參考下2015-07-07python 爬取免費(fèi)簡歷模板網(wǎng)站的示例
這篇文章主要介紹了python 爬取免費(fèi)簡歷模板網(wǎng)站的示例,幫助大家更好的理解和使用python 爬蟲,感興趣的朋友可以了解下2020-09-09