我的表“info”有4列:bp,key,exp和job。我正在尝试创建一个在指定列中搜索术语的函数:
编辑:不同的问题,请参阅第二个代码和第二个错误
def search2(query, field):
search_string = query
if field == "bp":
cursor.execute("SELECT * FROM info WHERE bp="+search_string)
elif field == "key":
cursor.execute("SELECT * FROM info WHERE key="+search_string)
elif field == "exp":
cursor.execute("SELECT * FROM info WHERE exp="+search_string)
elif field == "job":
cursor.execute("SELECT * FROM info WHERE job="+search_string)
然而,这会引发错误,“test”作为搜索字符串,“bp”作为列:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\user\Programs\time_database.py", line 32, in search2
cursor.execute("SELECT * FROM info WHERE bp="+search_string)
sqlite3.OperationalError: no such column: test
顺便说一下,“测试”不是一个专栏。我希望它是匹配指定列的搜索字符串...
修改的
感谢Martijn Pieters,但现在又出现了另一个错误。我现在的代码是:
def search2(query, field):
search_string = query
if field == "bp":
cursor.execute("SELECT * FROM info WHERE job=?", search_string)
elif field == "key":
cursor.execute("SELECT * FROM info WHERE key="+search_string)
elif field == "exp":
cursor.execute("SELECT * FROM info WHERE exp="+search_string)
elif field == "job":
cursor.execute("SELECT * FROM info WHERE job="+search_string)
我得到的错误是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\gummi\Programs\time_database.py", line 32, in search2
cursor.execute("SELECT * FROM info WHERE job=?", search_string)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
答案 0 :(得分:4)
您没有引用搜索字符串,而数据库正在将其解释为列名。
使用查询参数,这些参数会自动引用您的搜索字符串:
cursor.execute("SELECT * FROM info WHERE job=?", search_string)
接下来,如果field
(列)值不是来自不受信任的来源(例如网页),则可以将其直接插入到查询中:
cursor.execute("SELECT * FROM info WHERE %s=?" % field, (search_string,))
现在您不再需要所有分支。
如果field
值 来自不受信任的来源,最简单的方法就是测试它是否为允许值:
def search2(query, field):
if field not in set(['bp', 'key', 'exp', 'job']):
raise ValueError('No such column ' + field)
cursor.execute("SELECT * FROM info WHERE %s=?" % field, (query,))