如何使用MySQLdb创建外键

时间:2016-12-21 19:17:35

标签: python mysql mysql-python

导入MySQLdb模块后,我继续连接到MySQl Maria db:

import  MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")

现在我要创建两个表:WritersReaders。我希望Readers具有外键属性" Writer_id"这将指向相应的Writer:

with db:
    cHandler=db.cursor()
    cHandler.execute( "CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT)")
    cHandler.execute( "CREATE TABLE Readers(Id INT PRIMARY KEY AUTO_INCREMENT, FOREIGN KEY(Writer_id) REFERENCES Writers(Id) ) ")

但代码失败并出现错误:

_mysql_exceptions.OperationalError: (1072, "Key column 'x' doesn't exist in table")

错误在哪里?

2 个答案:

答案 0 :(得分:1)

with db:
    cHandler=db.cursor()

    cHandler.execute("DROP TABLE IF EXISTS Writers")
    cHandler.execute("DROP TABLE IF EXISTS Readers")

    cHandler.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, name TEXT)")
    cHandler.execute("CREATE TABLE Readers(Id INT PRIMARY KEY AUTO_INCREMENT, name TEXT, Writer_id INTEGER, FOREIGN KEY(Writer_id) REFERENCES Writers(Id))")

答案 1 :(得分:0)

您必须首先在Readers表中创建writer_id,然后将其设置为外键。

cHandler.execute( "CREATE TABLE Readers(Id INT PRIMARY KEY AUTO_INCREMENT, Writer_id INT ) ")
cHandler.execute( "alter table Readers
add foreign key (Writer_id)
references Writers(Id)")