向多个sql表添加数据帧(一个表与另一个表具有forienkey关系)

2024-10-01 00:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试通过sqlalchemy将pandas数据框上载到sql表。我应该在sql表中插入数据框的几列,然后读取主id,并根据该id将其他列插入到另一个表中。到目前为止,我已经尝试:

df1= df[['date','name','email','contact']]
before inserting the dataframe:
df['recordid']=  pd.read_sql_query('select MAX(recordid)+1 from table1', conn).iloc[0, 0] +range(len(df))
and then:
df1.to_sql('table1',conn, if_exists='append',index=False)

after inserting the dataframe1 which is a subset of main dataframe:
I'm adding date column to the main df as that is a notnull column in the table:
current_date = datetime.datetime.now()
df['enterdate'] = current_date
df2 = df[['date', 'recordid', 'ph.no', 'email', 'enterdate', 'query']]
df.to_sql('table2',conn, if_exists='append', index=False')

实际上,表2中的记录id是表1中的外键

我尝试的方法违反了唯一密钥约束“UQ_uuuleadentr_uuu28702c40b5ab9b80”。无法在对象错误中插入重复键

无法理解是否有更好的方法,以及我错在哪里


Tags: theto数据iddataframedfsqldate