1

我正在运行以下代码将 CSV 数据插入到 oracle DB 中。代码执行良好,直到生成 CSV 文件。

DEFAULT_CONFIG = "~/.oci/config"
DEFAULT_PROFILE = "DEFAULT"
config_file="config.json"
atp_dict_data=[]

db_username = "xx"
db_password = "xx"
db_type = "xx"

class DbConnect(object):
    comp_db_map = {}
    cx_Oracle.init_oracle_client(lib_dir="./instantclient_19_8")
   
    def __init__(self, db_username, db_password, db_type):
        self.db_username = db_username
        self.db_password = db_password
        self.db_type = db_type
        self.pool = cx_Oracle.SessionPool( db_username, db_password, db_type,min=1,max=10,increment=0,encoding='UTF-8')
    
    def get_connection(self):
        return self.pool.acquire()
    
    def select_from_db(self):
        sql = ('SELECT * FROM TT.PMP WHERE TE = "sall"');
        connection=self.get_connection()
        with connection.cursor() as cursor:
            cursor.execute(sql)
            connection.commit()
        return "executed"

    def insert_csv_data(self):
        //not sure how to insert data from csv

def config_file_parser(config_file):
    global atp_dict_data
    ab=[]
    config=configparser.ConfigParser()
    config.read(config_file)
    profile=config.sections()
    for config_profile in profile:
        func1 = get_work_request(file=config_file, profile_name=config_profile)
        #get_print_details(func1)


def get_work_request(file=DEFAULT_CONFIG, profile_name=DEFAULT_PROFILE):
    global oci_config, identity_client, work_request_client, atp_dict_data
    oci_config = oci.config.from_file(file, profile_name=profile_name)
    identity_client = oci.identity.identity_client.IdentityClient(oci_config)
    core_client = oci.core.ComputeClient(oci_config)
    db_client= oci.database.DatabaseClient(oci_config)
    atp_db_details = db_client.list_autonomous_databases(oci_config["compartment"]).data
    json_response = json.loads(str(atp_db_details))
    for i in json_response:
        
        atp_dict_data.append({'region': oci_config["region"], 'atp_name': i["db_name"], 'ser':oci_config["ser"], 'm_start': i["m_start"], 'm_end': i["m_end"]})
    
    print(atp_dict_data)
    keys = atp_dict_data[0].keys()
    with open('test.csv', 'w') as output_file:
        dict_writer = csv.DictWriter(output_file, keys)
        dict_writer.writeheader()
        dict_writer.writerows(atp_dict_data)

if __name__ == "__main__":
    config_file_parser(config_file)
    atp_conn = DbConnect(db_username, db_password, db_type)
    atp_conn.__init__
    atp_conn.get_connection
    atp_conn.select_from_db

问题 :

  1. 当我调用 Dbconnect 类时,它甚至不执行它只是执行直到atp_conn.__init__停止。

  2. 如何将 CSV 数据文件插入 Oracle DB?有没有更好的方法,例如不生成 CSV 文件并通过atp_dict_data使用 instaclient 连接从 dict ( ) 读取直接插入数据。

任何帮助都会很棒

4

1 回答 1

0

我认为您只需添加类似于我在下面向您展示的代码并将其封装到您的函数中。

请记住,以下只是一个示例,您必须使其适应您的特定代码

最简单的使用方法csv

import cx_Oracle
import csv

con = cx_Oracle.connect('hr/hrpsw@localhost/orcl')
cur = con.cursor()
with open("mycsvfile.csv", "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='|')
    # skip first line if header row
    next(csv_reader)
    for lines in csv_reader:
        cur.execute(
            "insert into table (field1, field2, ..... , fieldn ) values (:1, :2, ..... , :n)",
            (lines[0], lines[1], lines[2], ....., lines[n]))

cur.close()
con.commit()
con.close()

使用pandas

import pandas as pd
import cx_Oracle 

my_data = pd.read_csv('mycsvfile')
my_data.head()

from cx_Oracle import DatabaseError
try:
    conn = cx_Oracle.connect('yourconnectiondetails')
    if conn:
        cursor = conn.cursor()
        for i,row in my_data.iterrows():
            sql = "INSERT INTO table (field1, field2, ..... , fieldn ) values (:1, :2, ..... , :n)"
            cursor.execute(sql, tuple(row))
        # the connection is not autocommitted by default, so we must commit to save our changes
        conn.commit()
        print("Record inserted succesfully")
except DatabaseError as e:
    err, = e.args
    print("Oracle-Error-Code:", err.code)
    print("Oracle-Error-Message:", err.message)
finally:
    cursor.close()
    conn.close()
于 2021-09-29T15:49:03.530 回答