2017-07-04 54 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)