python - 具有可变数量占位符的安全 INSERT

标签 python sqlite

使用 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")

最佳答案

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"

关于python - 具有可变数量占位符的安全 INSERT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101869/

相关文章:

python - 与 while 循环中 if 条件的输出混淆

python - 如何通过匹配 BeautifulSoup 中元素属性中的文本来获取元素

python - 使用 boto3 删除 CloudFront 分配

python - [Python]按字母顺序排列名称

ruby-on-rails - 尝试显示时间时出现NoMethodError

python - Django 中的多对一关系

sql - 在SQLite中滥用聚合

c# - LINQ to Entities 不支持指定的类型成员 'Date'。(使用 Sqlie)

iphone - 如何在 SQLite 中更新此列?

java - 从 JAVA 中的游标获取 SQL 命令(android)