使用外键创建表

时间:2014-03-05 07:56:58

标签: 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

我想测试我的功能并编写以下代码。 “visit”和“test”只是包含一些列的表。在表“test_result”中,它包含“visit”表中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()

1 个答案:

答案 0 :(得分:0)

打印功能的实际输出时:

>>> createSQLCreateTableCommand("test_result",["value text","time_date text"],["visit int","test int"])
CREATE TABLE IF NOT EXISTS test_result (
    value text,
    time_date text,
    FOREIGN KEY (v) REFERENCES i(s),
    FOREIGN KEY (t) REFERENCES e(s)
)

您会看到像fk[0]这样的表达式从字符串中提取单个字符。

参数foreignKeys必须是由三个字符串组成的数组:子列名,父表名和父列名:

>>> print createSQLCreateTableCommand("test_result",
...                                   ["value text", "time_date text"],
...                                   [("visitid", "visit", "visitid"),
...                                    ("testname", "test", "name")])
CREATE TABLE IF NOT EXISTS test_result (
    value text,
    time_date text,
    FOREIGN KEY (visitid) REFERENCES visit(visitid),
    FOREIGN KEY (testname) REFERENCES test(name)
)

但是,这不是有效的SQL,因为FOREIGN KEY约束必须引用子表中的现有列。

要解决此问题,请更改createSQLCreateTableCommand函数以创建具有外键列约束的列:

>>> def createSQLCreateTableCommand(tableName, columns, foreignKeys):
...     columns = ["%s"%(c) for c in columns]
...     foreignKeys = ["%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
...
>>> print createSQLCreateTableCommand("test_result",
...                                   ["value text", "time_date text"],
...                                   [("visitid text", "visit", "visitid"),
...                                    ("testname text", "test", "name")])
CREATE TABLE IF NOT EXISTS test_result (
    value text,
    time_date text,
    visitid text REFERENCES visit(visitid),
    testname text REFERENCES test(name)
)