2014-03-05 72 views
0

我曾嘗試使用下面的代碼創建一個表的表,和它的作品創建一個表和值插入

def createSQLCreateTableCommand(tableName, columns, foreignKeys): 
    columns = ["%s"%(c) for c in columns] 
    foreignKeys = ["FOREIGN KEY (%s) REFERENCES %s(%s)"%(fk[0],fk[1],fk[2]) for fk in foreignKeys] 
    cmd = """CREATE TABLE IF NOT EXISTS %s (%s)"""%(tableName,','.join(columns+foreignKeys)) 
    return cmd 


sqlEx = createSQLCreateTableCommand("class",[ 
      "name text", 
      "role text"], 
      []) 
conn = sqlite.connect(":memory:") 
cursor = conn.cursor() 

cursor.execute(sqlEx) 

cursor.execute("""SELECT tbl_name FROM sqlite_master WHERE type = 'table'""") 
print cursor.fetchall() 

然後,我想一些值插入表中,我寫了下面的函數,但它給出了錯誤消息「表類沒有名爲'name','role'」的列。我很困惑,因爲我在前面的函數中創建了一個表,並且它工作正常。

def createSQLInsertCommand(tableName,columns): 
    columns = ["%s"%(c) for c in columns] 
    cmd = """INSERT INTO %s (%s) Values (?)""" %(tableName,columns) 
    return cmd 

sqlValidate = createSQLInsertCommand("class",["name","role"]) 

cursor.executemany(sqlValidate,[("Brian","Instructor"),("Steven","TA"),("Bob","TA"),("Jody","Student")]) 
cursor.execute("""SELECT * from class""") 
print cursor.fetchall() 

任何人都可以幫我修復我的第二個功能嗎?

回答

0

這裏是你的函數是做錯了,以及如何解決它

>>> columns = ["name","role"] 
>>> tableName = 'class' 
>>> """INSERT INTO %s (%s) Values (?)""" %(tableName,columns) 
"INSERT INTO class (['name', 'role']) Values (?)" 
>>> """INSERT INTO %s (%s) Values (?)""" %(tableName,','.join(columns)) 
'INSERT INTO class (name,role) Values (?)' 

此外,如果要插入2列,你必須應基於列例如可以產生2個?佔位符。

>>> """INSERT INTO %s (%s) Values (%s)""" %(tableName,','.join(columns), ','.join(['?' for c in columns])) 
'INSERT INTO class (name,role) Values (?,?)' 
相關問題