問(wèn)題描述
我知道可以使用帶有值元組的變量在 SQLite 數(shù)據(jù)庫(kù)中插入許多列值 ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)
和查詢字符串中相應(yīng)的占位符 (?, ?, ?, ?, ?)
.我正在我的程序中動(dòng)態(tài)創(chuàng)建值元組,它們最多可容納約 300 個(gè)值.我想知道是否有一種安全的(關(guān)于 SQL 注入攻擊)方法來(lái)動(dòng)態(tài)生成相應(yīng)的占位符元組字符串 (?, ?, ?, ...)
為查詢字符串?我要求這樣做是為了避免在我的數(shù)據(jù)庫(kù)結(jié)構(gòu)和值元組在整個(gè)開(kāi)發(fā)過(guò)程中發(fā)生變化時(shí)繁瑣地計(jì)數(shù)、添加和刪除 ?
.謝謝你的想法.
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.
推薦答案
根據(jù) values
中項(xiàng)目的數(shù)量構(gòu)建一個(gè)字符串,例如:
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)
如果它不符合您的架構(gòu),您就會(huì)遇到問(wèn)題,但這是另一個(gè)問(wèn)題...
If it doesn't meet your schema, you'll have issues, but that's another problem...
這篇關(guān)于動(dòng)態(tài)創(chuàng)建占位符以在 SQLite 表中為一行插入多個(gè)列值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!