2

我的表“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.
4

1 回答 1

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,))
于 2012-08-21T14:23:29.433 回答