笔者从外部获取dataframe类型的数据,尝试各种办法,要么各种报错,要么效率很低;
参照一海外大神文章,寥寥几句,完成任务
import cx_Oracle
import numpy as np
def df2db_insert(p_table_name,p_dataframe):
#准备数据,将待插入的dataframe转成list,以便多值插入
tmp_list=np.array(p_dataframe).tolist()
#准备sql窜 形如 insert into table_name(a,b,c) values(:a,:b,:c)
sql_string='insert into {}({}) values({})'.format(p_table_name,','.join(list(p_dataframe.columns)),','.join(list(map(lambda x:':'+x ,p_dataframe.columns))))
#准备数据库连接,并插入数据库
try:
with cx_Oracle.connect('quant/quant@quant',encoding='UTF-8') as conn:
with conn.cursor() as cursor:
cursor.executemany(sql_string,tmp_list)
conn.commit()
except cx_Oracle.Error as error:
print('Error occurred:')
print(error)
调用也简单,适用各种dataframe 的插入
test_df=...
df2db_insert('STOCK_BASIC',test_df)