def append_replace_sqldata(con, data, table_name, unique_columns,update_columns): ''' con:数据库连接 data:DataFrame数据表 table_name:所需要存储的目标表 unique_columns:联合主键或者唯一索引 update_columns:需要更新的列名 ''' # 构建 SQL 语句 columns = ', '.join(data.columns) values_placeholders = ', '.join(['?'] * len(data.columns)) update_clause = ', '.join([f"{column} = ?" for column in update_columns]) upsert_sql = f""" INSERT INTO {table_name}({columns}) VALUES ({values_placeholders}) ON CONFLICT({','.join(unique_columns)}) DO UPDATE SET {update_clause} """ for i, row in data.iterrows(): row_values = tuple(row) try: con.execute(upsert_sql, row_values + tuple(row[update_columns])) con.commit() # 提交事务 print("数据插入成功") except Exception as e: print(f"数据插入失败,错误信息:{e}") return
03-26
2873
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-22
5274
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-29