我试图通过将熊猫Dataframe插入MySQL(社区版)来更新玩家表。该查询适用于我要插入的标准数据/信息(int和str),但是我正在努力寻找一种解决方案,以便在引用团队表的同时在“团队”列中添加外键(多个玩家可以玩一队)。
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()
我不确定我是否将2和2放在一起,并按照我的方法得出8,但是对于实现该目标的任何方向将不胜感激。
答案 0 :(得分:0)
您已经注意到,必须先获取最后插入的ID。第二次插入之前,必须
Django有一些可能得到它 像https://stackoverflow.com/questions/14832115/get-the-last-inserted-id-in-djang
如果where子句没有用户输入,那么另一个选项可以使用select max(id)语句而不是%s