Insert Data To Oracle Table By Python

本文介绍了一种使用Python脚本将CSV文件中的数据批量导入到Oracle数据库的方法。该脚本利用cx_Oracle库连接Oracle数据库,并通过读取CSV文件逐行插入数据。此过程涉及错误代码的读取及格式化处理,适用于需要频繁更新数据库的应用场景。

This is an example to read the data from a CSV file and insert the data to a Oracle table using python script.

 

 

 

There are several ways to perform a batch insert into an Oracle database using Excel data: #### Method 1: Using SQL Developer 1. **Prepare the Excel data**: Ensure that the Excel data is in a tabular format with column headers that match the column names in the target Oracle table. 2. **Open SQL Developer**: Connect to the Oracle database where you want to insert the data. 3. **Import the Excel file**: In SQL Developer, go to `Tools` -> `Data Import Wizard`. Select the Excel file in the wizard. 4. **Map columns**: Map the columns from the Excel file to the columns in the target Oracle table. 5. **Execute the import**: Review the settings and click `Finish` to perform the batch insert. #### Method 2: Using Python with the `cx_Oracle` library ```python import cx_Oracle import pandas as pd # Read Excel data excel_file = pd.ExcelFile('your_excel_file.xlsx') df = excel_file.parse('Sheet1') # Connect to Oracle database dsn = cx_Oracle.makedsn(host='your_host', port=1521, sid='your_sid') connection = cx_Oracle.connect(user='your_user', password='your_password', dsn=dsn) # Prepare the insert statement columns = ', '.join(df.columns) values = ', '.join([':' + str(i + 1) for i in range(len(df.columns))]) insert_query = f"INSERT INTO your_table ({columns}) VALUES ({values})" # Convert DataFrame to a list of tuples data = [tuple(row) for row in df.values] # Execute the batch insert cursor = connection.cursor() cursor.executemany(insert_query, data) connection.commit() # Close the cursor and connection cursor.close() connection.close() ``` #### Method 3: Using SQL Loader 1. **Prepare a control file**: Create a control file (e.g., `control.ctl`) that describes the structure of the Excel data and how it maps to the Oracle table. ```plaintext LOAD DATA INFILE 'your_excel_file.csv' INTO TABLE your_table FIELDS TERMINATED BY ',' ( column1, column2, ... ) ``` 2. **Convert Excel to CSV**: Save the Excel file as a CSV file. 3. **Run SQL Loader**: Use the `sqlldr` command in the command line to perform the batch insert. ```bash sqlldr userid=your_user/your_password control=control.ctl ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值