虹影,夏至习俗,逐梦郁金香
c=db.cursor()
max_price=5
c.execute("""select spam, eggs, sausage from breakfast
where price < %s""", (max_price,))
注意,上面的sql字符串与后面的tuple之间的分隔符是逗号,平时拼写sql用的是%。
如果按照以下写法,是容易产生sql注入的:
c.execute("""select spam, eggs, sausage from breakfast
where price < %s""" % (max_price,))
这个和php里的pdo是类似的,原理同mysql prepared statements。
python
using the , 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.
'qmark' question mark style, e.g. '...where name=?' 'numeric' numeric, positional style, e.g. '...where name=:1' 'named' named style, e.g. '...where name=:name' 'format' ansi c printf format codes, e.g. '...where name=%s' 'pyformat' python extended format codes, e.g. '...where name=%(name)s'
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 ?
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
-
-
-
python中def是做什么的
python使用def开始函数定义,紧接着是函数名,括号内部为函数的参数,内部为函数的 具体功能实现代码,如果想要函数有返回值, 在expressions中的逻...
[阅读全文]
-
-
-
-
-
-
网友评论