Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用mysql.connector插入外键关系的更好方法是什么?_Python_Mysql_Foreign Keys - Fatal编程技术网

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

Python 使用mysql.connector插入外键关系的更好方法是什么?,python,mysql,foreign-keys,Python,Mysql,Foreign Keys,我想用外键连接两个表 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 &

我想用外键连接两个表

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


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

您不能将其用于替换占位符

如果用户名不是唯一的,则此查询将失败,只允许返回1个id

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

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

你不能用它来代替占位符

如果用户名不是唯一的,则此查询将失败,只允许返回1个id

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

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

好的,我想如果你能把代码分解成更小的小块,看起来会更整洁,但是如果是这样的话,谢谢你的回复。你可以在之前运行查询并获取数据。但这两者结合起来效果更好。好吧,我想如果你能把代码分解成更小的小块,看起来会更整洁,但是如果是这样的话,谢谢你的回复。你可以在之前运行查询并获取数据。但这两者结合起来效果更好。请