簡體   English   中英

Python和MySql,將數據插入通過外鍵連接的兩個表中的另一種方法

[英]Python and MySql, alternative way to insert data into two tables that connected by for foreign key

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

    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")

使用db.insert_id()獲取最后插入的id / customer_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM