python-sqlite3之占位符

The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).

execute(sql[, parameters])

sqlite3模块支持两种占位符:?占位符 和 有名占位符。

但是在使用 ?占位符时,要注意一点 当传入一个参数且该参数是字符串时,要将该字符串转换为 列表或元组。

 

验证过程如下:仔细看注释并运行

 1 #作为列表
 2 #像如下这种方式表示的占位符,那么需要将?看做一个接收list的参数
 3 sql = "UPDATE a SET para=? WHERE input_id=1"
 4 #c.execute(sql, ["hello"])
 5 #c.execute(sql, [string_new])
 6 #c.execute(sql, "hello")
 7 ##sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 5 supplied.
 8 ##从这个报错信息可以看出:将传入的占位符参数作为列表,current statement 只使用 0位置的元素,但是提供了5个元素,而占位符又只有一个,只需插入一个元素即可,其他多的元素不知道怎么处理,就报错了
 9 c.execute(sql, ("hello",))
10 
11 ##作为元组
12 #sql = "UPDATE a SET para=(?) WHERE input_id=1"
13 ##c.execute(sql, ("hello1",))
14 ##c.execute(sql, (string_new,))
15 ##c.execute(sql, ["hello"])
16 #c.execute(sql, [string_new])
17 
18 #?占位符总结
19 #execute(sql,parameters)中传入一个字符串时,不能直接将字符串作为parameter传入,要将其转换为列表或元组;否则sqlite3会将 字符串中的每一个字符作为一个parameter
20 
21 #有名占位符
22 #sql = "UPDATE a SET para=:str WHERE input_id=1"
23 #c.execute(sql, {"str":string_new})

 

posted @ 2018-05-27 16:56  suonikeyinsu  Views(7834)  Comments(0Edit  收藏  举报