首页 > 解决方案 > 如何使用用户指定的列构建 SQL Select 语句?

问题描述

我想按用户指定的名称选择列,但我想避免 SQL 注入。

我认为这样的事情不是一个好主意:

column_one = input("Column one")
column_two = input("Column two")
column_three = input("Column three")
sql.execute("Select {}, {}, {} from table;".format(column_one, column_two, column_three))

我可以使用类似的东西:

con = sql.connect("example.sqlite3")

select = "select ? from table;" 

t = ('id', ) 

cur = con.cursor() 
cur.execute(selec, t) 
rows = cur.fetchall() 
con.commit() 
con.close() 

for row in rows: 
    for cell in row: 
        print(cell)

我得到的是: id id id id id id id ...

标签: pythonsqlite

解决方案


编写查询以返回表中的所有列,然后使用条件逻辑选择要返回的列。


推荐阅读