2015-08-19 177 views
1

使用Python的sqlite3庫數量可變的安全INSERT,我可以在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") 
+1

「 」連接([「?」] * ColCount)將創建一個字符串 「?,?,?」,其中有多少?角色匹配ColCount。這有幫助嗎? – user3757614

+1

是的。謝謝!我最後做了一個for循環:範圍內的cols(1,len(ColumnData)): qmark + =「,?」後面跟着:c.execute('''INSERT INTO {tn} VALUES({q})'''.format(tn = TableName,q = qmark),ColumnData) – reliableJ

回答

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"