Python和MySql,将数据插入两个表中的替代方法,这两个表通过for foreign key连接

2024-06-28 20:25:48 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我用外键连接了两个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")

Tags: selfidexecutedbcustomerproductcursor外键