MySQL Forums
Forum List  »  Connector/Python

Re: mysql transactions - foreign key failure
Posted by: Geert Vanderkelen
Date: September 28, 2009 05:59AM

Hey Aaron,

I made a small example, showing transaction and foreign key.
Note:
1) Using InnoDB storage engine
2) Explicit commit

Hope this helps.

-Geert

table1 = """CREATE TABLE t1 (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
c1 INT,
PRIMARY KEY (id)
) ENGINE=InnoDB
"""
table2 = """CREATE TABLE t2 (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
fid INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
INDEX (fid),
FOREIGN KEY (fid) REFERENCES t1(id)
) ENGINE=InnoDB"""
cursor = db.cursor()

cursor.execute("DROP TABLE IF EXISTS t2, t1")
cursor.execute(table1)
cursor.execute(table2)

stmt = "INSERT INTO t1 (c1) VALUES (%s)"
cursor.execute(stmt,(599,))
stmt = "SELECT LAST_INSERT_ID()"
cursor.execute(stmt)
lastId = cursor.fetchone()[0]
stmt = "INSERT INTO t2 (fid) VALUES (%s)"
cursor.execute(stmt,(lastId,))
db.commit()

cursor.execute("SELECT t1.*, t2.* FROM t1,t2 WHERE t2.fid = t1.id")

print cursor.fetchall()

cursor.close()

Geert Vanderkelen
Software Developer at Oracle

Options: ReplyQuote




Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.