


Detailed explanation of Python using cx_Oracle module to operate Oracle database
This article mainly introduces Python's use of the cx_Oracle module to operate the Oracle database. It analyzes in detail the downloading and installation of the cx_Oracle module and the connection to the Oracle database, executing SQL statements, stored procedures and other related operating techniques in the form of examples. Friends in need can refer to the following
The example in this article describes how Python uses the cx_Oracle module to operate the Oracle database. Share it with everyone for your reference, the details are as follows:
ORACLE_SID parameter, this parameter is used in the operating system, it describes the database instance we want to connect to by default, for a situation where there are multiple instances on a machine Next, you need to modify it before you can connect through conn/as sysdba, because the default instance name is used here.
In short, for example, your name is Xiao Ming, but you have many nicknames. Your parents call you Xiao Ming, but your friends all call you by your nickname.
Here your parents are the oracle instance, Xiao Ming is the sid, and service name is your nickname.
sid is used to distinguish each database from an instance, and service name is used for external links. They may be different, so pay attention to which name you get and use it appropriately, otherwise errors may occur when connecting to other databases remotely.
Preface
There are many modules that come with Python that manipulate files. We can read the data from the file and write the data to the file after processing. But for data management and analysis, databases are still more professional. If Python can be combined with a database, it can combine the advantages of both and improve efficiency.
The Oracle database is used at work. Python has a module cx_Oracle that can be connected to Oracle. To use cx_Oracle, you must download it first.
1. Download cx_Oracle
Python is an official website PyPI, which has a wealth of modules. cx_Oracle can be downloaded from PyPI. Open the PyPI URL https://pypi.python.org/pypi and search for cx_Oracle to find the module. Its download address is http://cx-oracle.sourceforge.net/. Of course, you can also download it through other ways.
You can use it after downloading.
2. Usage process
The simple usage process is as follows:
①.Reference module cx_Oracle
②.Connect to the database
③ .Get cursor
④.Use cursor for various operations
⑤.Close cursor
⑥.Close connection
The following is a simple example:
cx_Oracle.connect("Username/Password@Oracle Server IP/Oracle's SERVICE_NAME")
Get Oracle's SERVICE_NAME:
su - oracle #Switch to oracle user
env | grep ORACLE #Query ORACLE environment variables
ORACLE_SID=benguo # benguo is SERVICE_NAME
import cx_Oracle #引用模块cx_Oracle conn=cx_Oracle.connect('load/123456@localhost/ora11g') #连接数据库 c=conn.cursor() #获取cursor x=c.execute('select sysdate from dual') #使用cursor进行各种操作 x.fetchone() c.close() #关闭cursor conn.close() #关闭连接
Example:
#coding:utf-8 import cx_Oracle def main(): conn = cx_Oracle.connect("zebra/zebra@192.168.0.113/benguo") cur =conn.cursor() r= cur.execute("select * from userinfo") print print r.fetchone() if __name__ == '__main__': main()
3. Several usages
Python's operations on the database mainly include two aspects: one is to write data, and the other is to read data. The implementation of these two aspects can be achieved through SQL statements or stored procedures. Therefore, the main uses of cx_Oracle are:
①. Execute SQL statements
②. Call stored procedures and functions.
4. Execute SQL statements
Executing SQL statements is very simple, as can be seen from the above example. Use cursor.execute
to execute. Use fetchone or fetchall to read out the execution results.
The following example is an Insert statement using variable binding.
import cx_Oracle conn=cx_Oracle.connect('load/123456@loaclhost/ora11g') c=conn.cursor() x=c.execute('insert into demo(v) values(:1)',['nice']) conn.commit(); c.close() conn.close()
Variable binding is the same as Oracle's dynamic SQL. It uses a colon as the placeholder, which is: 1 in the code. Copying the variable is to pass Enter a List, which is ['nice'] in the code. How many variables there are, how many values should correspond to the list, and the numbers must be consistent, otherwise an error will be reported.
After execution, you can use one of the connection methods connect.commit()
to commit the transaction.
5. Call stored procedures and methods
Directly enter the code:
--存储过程代码: CREATE OR REPLACE PROCEDURE P_DEMO(V1 IN VARCHAR2, V2 OUT VARCHAR2) IS BEGIN V2 := V1; END;
#Python代码: import cx_Oracle conn=cx_Oracle.connect('load/123456@localhost/ora11g') c=conn.cursor() str1='nice' str2=' '#需要有值,即len(str2)>=len(str1) x=c.callproc('p_demo',[str1,str2]) print(str2) c.close() conn.close()
The cursor.callproc
method is used to call the stored procedure. In the above stored procedure, the value of a variable is of type OUT. In Python, when assigning a value to a variable of type OUT, the length of the variable cannot be less than that in the stored procedure.
--函数代码: CREATE OR REPLACE function F_DEMO(V1 VARCHAR2) RETURN VARCHAR2 IS BEGIN RETURN V1; END;
#Python代码: import cx_Oracle conn=cx_Oracle.connect('load/123456@localhost/ora11g') c=conn.cursor() str1='nice' str2=c.callfunc('f_demo',cx_Oracle.STRING,[str1]) print(str2) c.close() conn.close()
The method used to call the function is cursor.callfunc
. The difference between this and calling a stored procedure is that it requires specifying the type of transmission parameters.
End
Through cx_Oracle, Python and Oracle database can communicate with each other, so that the two can complement each other's strengths.
For example, Python can be used as a data collection tool. It can obtain data from the Web and files, and then save the data to the Oracle database for further analysis of the data on the Oracle database.
related suggestion:
Python uses the openpyxl library to modify the excel table data method
Python uses the email module to encode and decode emails
The above is the detailed content of Detailed explanation of Python using cx_Oracle module to operate Oracle 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

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

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.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.
