I have a sqlite database named StudentDB which has 3 columns Roll number, Name, Marks. Now I want to fetch only the columns that user selects in the IDE. User can select one column or two or all the three. How can I alter the query accordingly using 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
在代码中,
query
现在是一个元组,而不是str
,这就是错误的原因我假设您希望执行如下查询-
然后,您可以像这样更改sql查询(假设您想要和而不是或)——
并执行如下查询-
请确保在代码中定义了提供的
database
并包含数据库名称,并且studentDB
确实是表名而不是数据库名您应该控制查询的文本。如果要构建参数化查询,where子句的格式应始终为
WHERE colname=value [AND colname2=...]
或(更好的)WHERE colname=? [AND ...]
所以你想要:
相关问题 更多 >
编程相关推荐