使用mysql.connector插入外键关系的更好方法是什么?

问题描述

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

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)时我要插入一个元组

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

解决方法

您不能使用它来替换占位符。

如果用户名不是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()