Python 和 MySql,插入连接两个外键表的替代方法

1 投票
2 回答
1822 浏览
提问于 2025-04-17 16:08

你好,我把两个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")

2 个回答

1

使用 db.insert_id() 可以获取最后插入的ID或者客户ID。

撰写回答