3 回答

TA貢獻1851條經驗 獲得超3個贊
問題是你不能對值以外的事物使用參數化查詢(即)(不確定我是否使用了正確的術語):表名,列名和SQL關鍵字是被禁止的。:tab_name
where age > :max_age
還可以。where :some_col > :max_age
莫。where age :comparison_operator :max_age
是不行的。
現在,您可以使用字符串串聯或 f 字符串構建自己的查詢,但是...?? 這是一個巨大的,巨大的SQL注入風險。請參閱 Bobby 表 更不用說,當您必須處理字符、數字或 None 時,將值連接到 SQL 查詢字符串中會很快遇到問題。(無 = > NULL,字符需要引號,數字不需要)。
您可以使用字符串替換來構建查詢,這些字符串替換僅接受表名和列名的已知值,然后使用 上的參數化查詢驅動刪除條件值。:value
(雖然這似乎具有限制性,但讓隨機調用方確定要刪除的表根本不安全)。
像這樣:
delete_tables(tab_name,attr,value):
safe_tab_name = my_dict_of_known_table_names[tab_name]
safe_attr = my_dict_of_known_column_names[attr]
# you have to `=`, not `is` here??
qry = f"delete from {safe_tab_name} where {safe_attr} = :value "
# not entirely sure about SQLite's bind/parametrized syntax.
# look it up if needed.
c.execute(qry, dict(value = value))
假設用戶只直接輸入值,則至少可以防止SQL注入。

TA貢獻1858條經驗 獲得超8個贊
您需要查看將在python方法中執行的確切SQL命令。對于方法調用delete_tables(“部分”、“sec_name”、“S1”),將生成的 SQL 命令將是
delete from table=section where attribute=sec_name is value=S1
這將是 SQL 中的無效命令。正確的命令應該是
delete from section where sec_name='S1'
因此,您需要相應地更改python函數。需要完成的更改應如下所示:
def delete_tables(tab_name, attr, value): c.execute("delete from :tab_name where :attr = ':value'", {'tab_name': tab_name, 'attr': attr, 'value':value})

TA貢獻1831條經驗 獲得超9個贊
def delete_tables(tab_name, attr, value): c.execute("delete from " + tab_name + "where " + attr + " = " + value)
我認為這樣的事情會起作用,問題是你試圖修改一個屬性,但它的名稱總是 ,為此你想把它變成一個參數,以便正確處理它。attribute
希望它有所幫助。
編輯:
檢查這個SQLite蟒蛇
c.execute的作用是“執行”一個SQL查詢,所以,你可以做一些類似你有表的東西。c.execute("select * from clients")
clients
execute
進行查詢并為您帶來結果集(如果是這種情況),因此,如果要使用常規SQL查詢從表中刪除,請在控制臺中鍵入,該語句將刪除id等于12的客戶端。delete from clients where client_id = 12
現在,如果你在蟒蛇中使用SQLite,你會做的
c.execute("delete from clients where client_id = 12")
但是,正如您希望它適用于任何表和任何字段(屬性)一樣,它會將表名,字段名稱和該字段的值轉換為變量。
tableName = "clients"
field = "client_id"
value = "12" #must be string because you would have to cast it from int in the execute
"""
if value is a varchar you must write
value = "'12'" because the '' are needed.
"""
c.execute("delete from " + tableName + " where " + field + " = " + value)
在頂部,您希望它是一個函數
def delete_tables(tableName, field, value):
c.execute("delete from " + tableName+ "where " + field + " = " + value)
編輯 2:
亞倫的評論是真的,它不安全,下一步你會做的是
def delete_tables(tab_name, attr, value):
#no ':value' (it limits the value to characters)
c.execute("delete from :tab_name where :attr = :value",
{'tab_name': tab_name, 'attr': attr, 'value':value})
這是來自瓦薩爾的答案
添加回答
舉報