python-sqlite3之占位符

2021/10/6 19:43:03

本文主要是介绍python-sqlite3之占位符,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

#作为列表
 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})
# https://www.cnblogs.com/black-mamba/p/9096519.html


这篇关于python-sqlite3之占位符的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程