当我在下面运行SQL查询时,出现错误 print(db.execute(“ SELECT * FROM(?);”),(tableName)) sqlite3.OperationalError:在“?”附近:语法错误
db = sqlite3.Connection(":memory:")
db.execute("CREATE TABLE Students(name);")
tableName = "Students"
var1 = "Jon"
var2 = "Steve"
var3 = "Chuckie"
db.execute("INSERT INTO Students VALUES (?), (?), (?)", (var1, var2, var3))
print(db.execute("SELECT * FROM (?);"), (tableName))
将参数传递给SQL查询的正确方法是什么?
答案 0 :(得分:0)
将值传递到元组中,
query = ("INSERT INTO billed_items(item_name,billed_qty,price,item_bill_series) VALUES(?,?,?,?)")
c.execute(query,((name),(no),(price),(series))
conn.commit()
答案 1 :(得分:0)
您不能在SQL中动态绑定对象名称,只能动态绑定值。对于这种行为,您将不得不求助于字符串操作:
queryTemplate = 'SELECT * FROM %s'
tableName = 'Students'
query = queryTemplate % tableName
print(query)
编辑:
为了解决评论中的问题-是的,此技术确实更容易受到SQL Injection攻击的攻击。在这种情况下,防止SQL注入的常见做法是使用允许表的白名单。
例如:
allowedTables = ['students', 'teachers']
if tableName not in allowedTables:
raise ValueError('Wrong table')