Reputation: 19349
After importing MySQLdb
module I go ahead and connect to MySQl Maria db:
import MySQLdb
db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="test")
Now I want to create two tables: Writers
and Readers
. I want Readers
to have a Foreign Key attribute "Writer_id" that would point to the corresponding 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) ) ")
But the code fails with the error:
_mysql_exceptions.OperationalError: (1072, "Key column 'x' doesn't exist in table")
Where is the error?
Upvotes: 0
Views: 6178
Reputation: 19349
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))")
Upvotes: 1
Reputation: 3186
you have to create writer_id in Readers table first and then set it as a foreign key after.
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)")
Upvotes: 0