Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

python - SQLite parameter substitution and quotes

I have this line that works OK:

c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name)

But I want to use SQLite parameter substitution instead instead of string substitution (because I see here that this is safer).

This is my (failed) try:

t = (name,)
c.execute('select cleanseq from cleanseqs WHERE newID="?"',t)

But this line returns:

'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'

So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.

So the question is: How do I convert this line:

c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To anyone who like me found this thread and got really frustrated by people ignoring the fact that sometimes you can't just ignore the quotes (because you're using say a LIKE command) you can fix this by doing something to the effect of:

var = name + "%"
c.execute('SELECT foo FROM bar WHERE name LIKE ?',(var,))

This will allow you to substitute in wildcards in this situation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...