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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM