简体   繁体   中英

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

team_id is the foreign key in the player table referencing a team table

#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.

As you noticed you have to get the last inserted id first.bwfore the second insert

Django has some possibilityies to get it Like 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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