1
我写一个函数来创建一个表:创建表与外键
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
我想测试我的功能和写下面的代码。 “访问”和“测试”只是一些列的表格。在表“test_result”中,它包含“访问”表中的rowid的外键以及“test”表中的rowid的外键。我的代码适用于“访问”和“测试”表,但未能证明“test_result”表。我不确定不能正确表达外键参数。任何人都可以帮助我解决我的代码?
conn = sqlite.connect(":memory:")
cursor = conn.cursor()
sqlVisits = createSQLCreateTableCommand("visit",["visitid text"],[])
sqlTests = createSQLCreateTableCommand("test",["name text","unit text","low text","high text"],[])
sqlTestResults = createSQLCreateTableCommand("test_result",["value text","time_date text"],["visit int","test int"]) #this is not correct
cursor.execute(sqlVisits)
cursor.execute(sqlTests)
cursor.execute(sqlTestResults)
conn.commit()
cursor.execute("""SELECT tbl_name FROM sqlite_master WHERE type = 'table'""")
print cursor.fetchall()