問題描述
我知道可以使用帶有值元組的變量在 SQLite 數據庫中插入許多列值 ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)
和查詢字符串中相應的占位符 (?, ?, ?, ?, ?)
.我正在我的程序中動態創建值元組,它們最多可容納約 300 個值.我想知道是否有一種安全的(關于 SQL 注入攻擊)方法來動態生成相應的占位符元組字符串 (?, ?, ?, ...)
為查詢字符串?我要求這樣做是為了避免在我的數據庫結構和值元組在整個開發過程中發生變化時繁瑣地計數、添加和刪除 ?
.謝謝你的想法.
I know that it's possible to insert many column values in a SQLite database using a variable with a tuple of values ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)
and a corresponding placeholder (?, ?, ?, ?, ?)
in the query string. I am creating the value tuples dynamically in my program and they may hold up to ~300 values. I am wondering if there is a safe (with respect to SQL injection attacks) way to dynamically generate corresponding the placeholder tuple string (?, ?, ?, ...)
for the query string? I ask this to avoid tediously counting, adding and deleting ?
s as my database structure and value tuples change throughout development. Thanks for your thoughts.
推薦答案
根據 values
中項目的數量構建一個字符串,例如:
Build a string based on the number of items in your values
, eg:
def place_holder(values):
return '({})'.format(', '.join('?' * len(values)))
values = ['a', 'b', 'c']
ph = place_holder(values)
# (?, ?, ?)
然后是這樣的:
your_cursor.execute('insert into your_table values {}'.format(ph), values)
如果它不符合您的架構,您就會遇到問題,但這是另一個問題...
If it doesn't meet your schema, you'll have issues, but that's another problem...
這篇關于動態創建占位符以在 SQLite 表中為一行插入多個列值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!