1. To enable Python to operate the Oracle database, first install the cx_Oracle package. You can obtain the installation package through the following address:
[Plain]
- Http://cx-oracle.sourceforge.net/
2. You also need some class libraries of oracle. You need to install the Oracle Instant Client package on the machine running python.
[Plain]
- Http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Find the package that meets your platform and install it. Here I use the rpm package, so run the following command to install
[Plain]
- $ Sudo rpm-ivh oracle-instantclient11.2-basic-11.2.0.3.0-1.i386.rpm
After installation, you need to set the environment variables as follows [plain]
- $ Export LD_LIBRARY_PATH =$ {LD_LIBRARY_PATH}:/usr/lib/oracle/11.2/client/lib
3. Create a simple python file and test whether the installation is successful. [python]
- ImportCx_Oracle
- Conn = cx_Oracle.connect ('Fkong/fkong@172.17.23.129/orcl')
- Cursor = conn. cursor ()
- Cursor.exe cute ("Select * from dual")
- Row = cursor. fetchone ()
- PrintRow [0]
- Cursor. close ()
- Conn. close ()
4. The following describes a database table creation and insertion Operation [python].
- ImportCx_Oracle
- Conn = cx_Oracle.connect ('Fkong/fkong@172.17.23.129/orcl')
- Cursor = conn. cursor ()
- Cursor.exe cute ("Create table test (id int, COL1 VARCHAR (32), COL2 VARCHAR (32), COL3 VARCHAR (32 ))")
- Cursor.exe cute ("Insert into test (ID, COL1, COL2, COL3) VALUES (1, 'A', 'B', 'C ')")
- Cursor.exe cute ("Insert into test (ID, COL1, COL2, COL3) VALUES (2, 'A', 'bb ', 'cc ')")
- Cursor.exe cute ("Insert into test (ID, COL1, COL2, COL3) VALUES (3, 'aaa', 'bbb ', 'ccc ')")
- Conn. commit ()
- Cursor. close ()
- Conn. close ()
5. next let's look at the query. there are usually two ways to query: one is to use cursor. fetchall () is used to obtain all query results and then iterate over one row. fetchone () gets a record until the obtained result is null. Let's look at the example below: [python]
- ImportCx_Oracle
- Conn = cx_Oracle.connect ('Fkong/fkong@172.17.23.129/orcl')
- Cursor = conn. cursor ()
- Cursor.exe cute ("SELECT * from test")
- Rows = cursor. fetchall ()
- ForRowInRows:
- Print "% D, % s"% (Row [0], Row [1], Row [2], Row [3])
- Print "Number of rows returned: % d"% Cursor. rowcount
- Cursor.exe cute ("SELECT * from test")
- While(1):
- Row = cursor. fetchone ()
- IfRow =None:
- Break
- Print "% D, % s"% (Row [0], Row [1], Row [2], Row [3])
- Print "Number of rows returned: % d"% Cursor. rowcount
- Cursor. close ()
- Conn. close ()