


Configure python to connect to oracle, read excel data and write it to the database
Prerequisite: Oracle single instance has been installed locally, and you can use plsql developer to connect, or you can use TNS connection string to remotely connect to the oracle cluster
Read excel and write There are many ways to enter the database. The one introduced here is to use pandas to write, which is relatively simple. There is no need to organize the data after reading excel
(free learning recommendation: python video tutorial)
The whole process needs to be carried out in two steps:
1. Configure python Connect to Oracle and test successfully
There are many tutorials on the Internet, but most of them are not so detailed, and they do not explain the difference between connecting to a single instance and connecting to a cluster. Here we first introduce the method of connecting to an Oracle single instance. , and the method of connecting to the Oracle cluster will be added later.
Version:
window 10 64-bit
python 3.6.8
cx-Oracle 7.3.0
Installation process:
1 . Use pip to install the package that operates Oracle:
pip install cx_Oracle==7.3.0
##2. Manually configure cx_Oracle temporarily Client:
Note that the computer here is 64-bit, and the instant client used is also 64-bit. For 32-bit, you need to go to the download address below to find it2.1. Unzip the following file
Link: https://pan.baidu.com/s/1ARcdK8kgNKfQsNbP5ZEbKg Extraction code: lz0g oracle instant client Client usage instructions:
https://docs.oracle.com/en/database/oracle/oracle-database/19/lnoci/instant-client.html#GUID-6895DB45-97AA-4738-9959-BD677D610186
Oracle instant client download address:
https://www.oracle.com/database/technologies/instant-client/downloads.html
If no data is found, it may be that there is no emp table under the user.
import cx_Oracleimport os# 设置环境编码方式,可解决读取数据库中文乱码问题os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'# 用户名/密码@IP:端口/实例名conn = cx_Oracle.connect('kplin/12sss3456@192.168.124.102:1521/ORCL')cursor = conn.cursor()try: sql = 'select * from emp' cursor.execute(sql) ret = cursor.fetchall() print(ret) # cursor.commit()except Exception as e: print(e)finally: cursor.close()
2. Use pandas to read excel data and use sqlalchemy to assist in writing to the database
1. Install sqlalchemy , pandas
The pandas version is specified here because the latest version of pandas will report some strange errors when reading and writing excel. Just change to version 1.1.4.pip install pandas==1.1.4pip install sqlalchemy
2. Prepare an excel table, named test.xlsx, and write the following test data
3 , test reading and writing to the database
#!/usr/bin/env python# -*- coding:utf-8 -*-# date: 2021/3/14# filename: excel_to_db# author: kplinimport pandas as pdfrom sqlalchemy import create_enginefrom sqlalchemy import types# conn_string='oracle+cx_oracle://user:pass@host:port/dbname'conn_string='oracle+cx_oracle://KPLIN:654321@192.168.124.6:1521/ORCL'engine = create_engine(conn_string, echo=False)df = pd.read_excel('test.xlsx')# if_exists有三个可选值,'fail':如果存在该表则报错,'append':如果存在该表则将数据追加到列尾,'replace':如果存在该表则替换# df.to_sql('test', con=engine, if_exists='replace')# 按上面这种写入方式name字段将被写成clob字段类型,# 如果我们希望把name改为varchar2类型,怎么做?# 我们可以利用sqlalchemy的types把name指定为varchar2()类型len = df.name.str.len().max()df.to_sql('test', engine, if_exists='replace', dtype={'name': types.VARCHAR(len)})rows = engine.execute("SELECT * FROM TEST").fetchall()print(rows)
Related free learning recommendations: python tutorial( video)
The above is the detailed content of Configure python to connect to oracle, read excel data and write it to the database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

MongoDB is suitable for handling large-scale unstructured data, and Oracle is suitable for enterprise-level applications that require transaction consistency. 1.MongoDB provides flexibility and high performance, suitable for processing user behavior data. 2. Oracle is known for its stability and powerful functions and is suitable for financial systems. 3.MongoDB uses document models, and Oracle uses relational models. 4.MongoDB is suitable for social media applications, while Oracle is suitable for enterprise-level applications.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
