根据sqlite-python中的用户选择更改查询



我有一个名为StudentDB的sqlite数据库,它有3列Roll number、Name和Marks。现在我只想获取用户在IDE中选择的列。用户可以选择一列、两列或全部三列。如何使用Python相应地更改查询?

我尝试过:

import sqlite3
sel={"Roll Number":12}
query = 'select * from StudentDB Where({seq})'.format(seq=','.join(['?']*len(sel))),[i for k,i in sel.items()]
con = sqlite3.connect(database)
cur = con.cursor()
cur.execute(query)
all_data = cur.fetchall()
all_data

我得到:

operation parameter must be str

您应该控制查询的文本。如果要构建参数化查询,where子句的格式应始终为WHERE colname=value [AND colname2=...]或(更好(WHERE colname=? [AND ...]

所以你想要:

query = 'select * from StudentDB Where ' + ' AND '.join('"{}"=?'.format(col)
for col in sel.keys())
...
cur.execute(query, tuple(sel.values()))

在您的代码中,query现在是一个元组,而不是str,这就是错误的原因。

我想你想执行下面这样的查询-

select * from StudentDB Where "Roll number"=?

然后,您可以像这样更改sql查询(假设您想要和不想要或(-

query = "select * from StudentDB Where {seq}".format(seq=" and ".join('"{}"=?'.format(k) for k in sel.keys()))

并执行类似-的查询

cur.execute(query, tuple(sel.values()))

请确保在您的代码中定义了提供的database并包含数据库名称,并且studentDB确实是表名称,而不是数据库名称。

最新更新