首页 > 数据库技术 > 详细

python-sqlite3之占位符

时间:2018-05-27 17:02:29      阅读:405      评论:0      收藏:0      [点我收藏+]

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})

 

python-sqlite3之占位符

原文:https://www.cnblogs.com/black-mamba/p/9096519.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!