创建一个表并将值插入表中

时间:2014-03-05 04:58:52

标签: python sqlite python-2.7

我使用以下代码创建了一个表,它可以正常工作

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()

然后,我想在表中插入一些值,并编写以下函数,但它给出了错误消息“table class没有列名为'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()

任何人都可以帮我修复我的第二个功能吗?

1 个答案:

答案 0 :(得分: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 (?,?)'