2013-02-17 76 views
1

您好,我使用外鍵連接了兩個MySql表,我想通過python向它們中插入數據。這裏是一段代碼,但應該有一個替代和專業的方式來做,否則我不需要外鍵,而只需插入第二張表的第一個表customer_id列的ID。感謝您的幫助。Python和MySql,將數據插入到通過外鍵連接的兩個表中的另一種方法

Product = str(self.Text.GetValue()) 
    Product2 = str(self.Description.GetValue())  
    db=MySQLdb.connect('127.0.0.1', 'root','password', 'database') 
    cursor = db.cursor() 
    cursor.execute("INSERT INTO customer (Address) VALUES (%s)", (Product)) 
    cursor.execute("SELECT id FROM customer ORDER BY id DESC LIMIT 1") 
    rows = cursor.fetchall() 
    the_id= rows[0][0] 
    cursor.execute("INSERT INTO product_order (customer_id, description) VALUES (%s,%s)", (the_id,Product2))   
    cursor.execute("commit") 
+1

專業地說,我會爲此使用一個框架。 – myusuf3 2013-02-17 03:31:26

回答

0

使用db.insert_id()獲得最後插入的ID/CUSTOMER_ID

0
+0

謝謝。我也喜歡這種方式,節省了幾行代碼。甚至還不知道那裏有什麼外鍵的好處。 – jesy2013 2013-02-17 03:48:51

+0

http://en.wikipedia.org/wiki/Data_integrity – 2013-02-17 04:11:02

相關問題