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()
任何人都可以幫我修復我的第二個功能嗎?