首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python Pandas的Oracle中的UPSERT

问使用Python Pandas的Oracle中的UPSERT
EN

Stack Overflow用户
提问于 2022-04-27 00:46:56
回答 1查看 434关注 0票数 1

我希望使用cx_Oracle和pandas读取包含验证数据集的csv,并根据主键将csv中的每条记录插入或更新到Oracle表中。如果csv中的主键列值为null,则该行中的每一列都将作为oracle中的新行插入,但如果主键列值不为null (已存在于oracle表中),那么我希望只为值为空(空)的列更新csv中的值。

例如,如果我的csv看起来如下(ID作为主键):

代码语言:javascript
复制
ID,FIRSTNAME,LASTNAME,AGE,SALARY
null,John,Smith,30,40000
2,James,Johnson,15,null

我需要插入第一行中的每一列,以便我的oracle表为它生成一个新的ID,但我只需要更新oracle表中带有ID=2的行的FIRSTNAME、LASTNAME、AGE。

如何生成新行的新ID (从表中现有的最高ID递增)和( 2 )根据csv中哪些列不为null来更新哪些列?

请注意,在更新/插入数据库之前,数据将导入数据。

EN

回答 1

Stack Overflow用户

发布于 2022-04-27 14:06:53

可以在数据库中使用MERGE语句,如

代码语言:javascript
复制
import cx_Oracle
import numpy as np
import pandas as pd
from pandas import DataFrame

con = cx_Oracle.connect('uname/pwd@host:port/service_name')
cursor = con.cursor()

dataset = pd.DataFrame({'id': [np.NaN,2],
                        'firstname': ['John','James'],
                        'lastname': ['Smith','Johnson'],
                        'age': [30,15],
                        'salary': [40000,np.NaN]
                       })

df_list = dataset.fillna('').values.tolist()
sql ='merge into employee using dual on ( id = :1 )';
sql+=' when matched then update set firstname = :2, lastname = :3, age = :4, salary = :5';  
sql+=' when not matched then insert values( :1, :2, :3, :4, :5 )';

for i in range(len(df_list)):
    cursor.execute(sql,df_list[i])

con.commit()

考虑到数据将被导入数据

或

直接从当前.csv文件中使用

代码语言:javascript
复制
import cx_Oracle
import numpy as np
import pandas as pd
from pandas import DataFrame

con = cx_Oracle.connect('uname/pwd@host:port/service_name')
cursor = con.cursor()

source_file = 'C:\\path\\To\\yourFile.csv'
df = pd.read_csv(source_file, sep = ",", dtype=str)
dataset = df.fillna('').values.tolist()    

sql ='merge into employee using dual on ( id = :1 )';
sql+=' when matched then update set firstname = :2, lastname = :3, age = :4, salary = :5';  
sql+=' when not matched then insert values( :1, :2, :3, :4, :5 )';

cursor.executemany(sql, dataset)

con.commit()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72022076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档