【问题标题】:What would be a better way to insert foreign key relations using mysql.connector?使用 mysql.connector 插入外键关系的更好方法是什么?
【发布时间】:2025-12-31 11:00:11
【问题描述】:

我想使用外键连接两个表。

my_cursor = db.cursor(prepared=True)
Q3 ="INSERT INTO bookings(userID, posts) VALUES (%s, %s)"
Q4 = "SELECT userID from users where username=%s"
my_cursor.execute(Q3, ((Q4, username), posts))
db.commit()

我收到以下错误。

File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 626, in prepare_for_mysql
    result = self._cmysql.convert_to_mysql(*params)
_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted

我猜这是有道理的,因为我在输入 (Q4, userID) 时插入了一个元组。

如何在将值作为外键引用时插入该值?

【问题讨论】:

    标签: python mysql foreign-keys


    【解决方案1】:

    你不能用它来代替占位符。

    如果用户名不是UNIQUE,这个查询会失败,只允许返回1个id

    我还添加了 my_cursor 定义,因为你没有提供你的

    my_cursor = connection.cursor(prepared=True)
    Q3= "INSERT INTO bookings(userID, posts) VALUES ((SELECT userID from users where username=%s), %s);"
    my_cursor.execute(Q3, ( username, posts))
    db.commit()
    

    【讨论】:

    • 好的,我认为如果可以将代码分解成更小的部分会看起来更整洁,但如果是这样的话,感谢您的回复。
    • 您可以在之前运行查询并获取数据。但结合起来效果更好。请accept the answer
    最近更新 更多