我希望使用cx_Oracle和pandas读取包含验证数据集的csv,并根据主键将csv中的每条记录插入或更新到Oracle表中。如果csv中的主键列值为null,则该行中的每一列都将作为oracle中的新行插入,但如果主键列值不为null (已存在于oracle表中),那么我希望只为值为空(空)的列更新csv中的值。
例如,如果我的csv看起来如下(ID作为主键):
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来更新哪些列?
请注意,在更新/插入数据库之前,数据将导入数据。
发布于 2022-04-27 14:06:53
可以在数据库中使用MERGE语句,如
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文件中使用
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()https://stackoverflow.com/questions/72022076
复制相似问题