简体   繁体   English

在插入pandas df的同时从另一个表插入外键

[英]INSERT foreign key from another table whilst inserting pandas df

I have trying to update a player table by inserting a pandas Dataframe into MySQL (community edition).我试图通过将 Pandas Dataframe 插入 MySQL(社区版)来更新玩家表。 The query works for the standard data/information (int and str) that I am inserting, but I am struggling to find the a solution to add a foreign key in a 'team' column whilst referencing a team table (multiple players can play for one team).该查询适用于我正在插入的标准数据/信息(int 和 str),但我正在努力寻找在引用团队表的同时在“团队”列中添加外键的解决方案(多个玩家可以玩一个团体)。

team_id is the foreign key in the player table referencing a team table team_id 是玩家表中引用团队表的外键

#connection to database
conn = mysql.connector.connect(host='localhost', user='root', passwd='passed')
cur = conn.cursor() #create cursor

#query statement to insert a list of teams to table
query_list_to_column = "INSERT IGNORE INTO team (team_name) VALUES (%s)"
#execute statements
cur.executemany(query_list_to_column, [(r,) for r in team_list]) #team lists to team table

#SQL statement to insert df into player table
sql_df_insert = """INSERT INTO player (`full_name`, `first_name`, `last_name`,
                                    `name_FIBA_format`, `dob`, `age`, `height`,
                                    `real_gm_profile`, `team_id`, `game_log_url`)
         VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

final_df = final_df.reindex(['full_name', 'first_name', 'last_name', 'name_FIBA_format',
                             'dob', 'age', 'height', 'real_gm_profile', (SELECT id from team WHERE team_name = 'team'), 'game_log_url'],
                            axis='columns')

cur.executemany(sql_df_insert, final_df.to_numpy().tolist())
conn.commit()

I am not sure if I am putting 2 and 2 together and getting 8 with how I have approached this, but any direction on how I would achieve this would be greatly appreciated.我不确定我是否将 2 和 2 放在一起并通过我如何处理这个得到 8,但是我将不胜感激任何关于我将如何实现这一目标的方向。

As you noticed you have to get the last inserted id first.bwfore the second insert正如您所注意到的,您必须先获取最后插入的 id。bwfore 在第二次插入之前

Django has some possibilityies to get it Like https://stackoverflow.com/questions/14832115/get-the-last-inserted-id-in-djang Django 有一些获得它的可能性 像https://stackoverflow.com/questions/14832115/get-the-last-inserted-id-in-djang

Another option can be using the select max(id) statement instead of the %s if the where clause doesn't have user input , it still is secure另一个选择是使用 select max(id) 语句而不是 %s 如果 where 子句没有用户输入,它仍然是安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM