2017-07-04 63 views
0

我对Mysql非常陌生,并且使用python在db中转储文件。我有2个表 的文件格式是:查询在mysql表中插入数据包含外键

id name sports 
1 john baseball 
2 mary Football 

像学生&体育 学生表

id name 
1  John 
2  Mary 

这里的id是主键

&体育台

stu_id sports_title 

1  Baseball 
2  Football 

这里stu_id是学生表

外键参考,我的问题是

query="insert into sports (stu_id,name)VALUES (%d,%s)" 
      ("select id from student where id=%d,%s") 
#words[0]=1 ,words[2]=Baseball 

args=(words[0],words[2]) 
cursor.execute(query,args) 

在执行这个代码,我面对

"Not all parameters were used in the SQL statement") 
ProgrammingError: Not all parameters were used in the SQL statement 
+0

请详细说明'单词'是什么。 –

+0

...以及'query'发生了什么。 – DeepSpace

+0

@IljaEverilä我猜'词是来自顶部显示的文件的行的字段。 – Barmar

回答

0

您不能同时使用VALUESSELECT作为INSERT中的数据来源。如果数据是文字,则使用VALUES;如果从另一个表中获取,则使用SELECT。如果它们混合使用,则使用SELECT并将文字放入SELECT列表中。

query = """ 
    INSERT INTO sports (stu_id, sports_title) 
    SELECT id, %s 
    FROM student 
    WHERE name = %s 
""" 
args = (words[2], words[1]) 
cursor.execute(args) 

或者,由于该文件包含了学生证,你不需要SELECT可言。

query = "INSERT INTO sports(stu_id, sports_title) VALUES (%d, %s)" 
args = (words[0], words[1]) 
cursor.execute(args)