【问题标题】:Safe INSERT with a variable number of placeholders具有可变数量占位符的安全插入
【发布时间】:2015-08-19 17:23:02
【问题描述】:

使用 Python 的 sqlite3 库,我可以在 SQL 语句中拥有可变数量的占位符吗:

INSERT INTO table VALUES (?,?)` 

其中? 是占位符,它可以免受SQL injection 攻击吗?

我希望能够有一个通用函数(如下)来检查列数并将数据写入一行,但它可以适用于具有任意列数的任何表。

我看了:

但我还是不确定。

def rowin(self, TableName, ColumnData=[]):
    # First check number columns in the table TableName to confirm ColumnData=[] fits
    check = "PRAGMA table_info(%s)"%TableName
    conn = sqlite3.connect(self.database_file)
    c = conn.cursor()
    c.execute(check)
    ColCount = len(c.fetchall())
    # Compare TableName Column count to len(ColumnData)

    if ColCount == len(ColumnData):
        # I want to be have the number of ? = ColCount
        c.executemany('''INSERT INTO {tn} VALUES (?,?)'''.format(tn=TableName), ColumnData)
        conn.commit()

    else:
        print("Input doesn't match number of columns")

【问题讨论】:

  • ",".join(["?"] * ColCount) 将创建一个字符串“?,?,?”,其中有多少个?字符匹配 ColCount。这有帮助吗?
  • 是的。谢谢!我最终首先做了一个 for 循环:for cols in range(1,len(ColumnData)): qmark += ",?"后跟:c.execute('''INSERT INTO {tn} VALUES ({q})'''.format(tn=TableName, q=qmark),ColumnData)

标签: python sqlite


【解决方案1】:
def rowin(self,TableName,ColumnData=[]):
        #first count number columns in the table TableName
        check = "PRAGMA table_info(%s)"%TableName
        conn = sqlite3.connect(self.database_file)
        c = conn.cursor()
        c.execute(check)
        #assing number of columns to ColCount
        ColCount = len(c.fetchall())
        #compare TableName Column count to len(ColumnData)
        qmark = "?"
        #first create a place holder for each value going to each column
        for cols in range(1,len(ColumnData)):
            qmark += ",?"
        #then check that the columns in the table match the incomming number of data
        if ColCount == len(ColumnData):
            #now the qmark should have an equl number of "?" to match each item in the ColumnData list input
            c.execute('''INSERT INTO {tn} VALUES ({q})'''.format(tn=TableName, q=qmark),ColumnData)
            conn.commit()
            print "Database updated"
        else:
            print "input doesnt match number of columns"

【讨论】:

    猜你喜欢
    • 2012-02-19
    • 2014-11-04
    • 2021-07-04
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2013-12-12
    • 1970-01-01
    相关资源
    最近更新 更多