1. To enable Python to operate the Oracle database, you first need to install the Cx_oracle package, which can be obtained from the address below
[Plain]View PlainCopy
- http://cx-oracle.sourceforge.net/
2. Additional Oracle class libraries are required to install the Oracle Instant client package on a machine running Python, which can be obtained from the following address
[Plain]View PlainCopy
- Http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Find the package that fits your platform, then install it, I'm using the RPM package, so install it using the following command
[Plain]View PlainCopy
- $ sudo rpm-ivh oracle-instantclient11.2-basic-11.2.0.3.0-1.i386.rpm
After the installation, you need to set the environment variables, as follows
[Plain]View PlainCopy
- $ Export Ld_library_path=${ld_library_path}:/usr/lib/oracle/11.2/client/lib
3. Create a simple Python file to test whether the installation was successful
[Python]View PlainCopy
- Import Cx_oracle
- conn = Cx_oracle.connect (' fkong/[email protected]/orcl ')
- cursor = Conn.cursor ()
- Cursor.execute ("SELECT * from dual")
- row = Cursor.fetchone ()
- Print row[0]
- Cursor.close ()
- Conn.close ()
4. Look at a Database build table and insert operation
[Python]View PlainCopy
- Import Cx_oracle
- conn = Cx_oracle.connect (' fkong/[email protected]/orcl ')
- cursor = Conn.cursor ()
- Cursor.execute ("CREATE TABLE TEST" (ID INT, COL1 varchar (+), COL2 varchar (), COL3 varchar (+)) ")
- Cursor.execute ("INSERT into TEST (ID, COL1, COL2, COL3) VALUES (1, ' A ', ' B ', ' C ')")
- Cursor.execute ("INSERT into TEST (ID, COL1, COL2, COL3) VALUES (2, ' AA ', ' BB ', ' cc ')")
- Cursor.execute ("INSERT into TEST (ID, COL1, COL2, COL3) VALUES (3, ' AAA ', ' BBB ', ' CCC ')")
- Conn.commit ()
- Cursor.close ()
- Conn.close ()
5. Here's a look at the query, there are usually two ways of querying: one is to get all the query results using Cursor.fetchall () and then one line of iterations, and the other one to get a record by Cursor.fetchone () until the result is empty. Take a look at the following example:
[Python]View PlainCopy
- Import Cx_oracle
- conn = Cx_oracle.connect (' fkong/[email protected]/orcl ')
- cursor = Conn.cursor ()
- Cursor.execute ("select * from TEST")
- rows = Cursor.fetchall ()
- For row in rows:
- print "%d,%s,%s,%s"% (row[0], row[1], row[2], row[3])
- Print "Number of rows returned:%d"% cursor.rowcount
- Cursor.execute ("select * from TEST")
- while (1):
- row = Cursor.fetchone ()
- if row = = None:
- Break
- print "%d,%s,%s,%s"% (row[0], row[1], row[2], row[3])
- Print "Number of rows returned:%d"% cursor.rowcount
- Cursor.close ()
- Conn.close ()
Oracle database operations for Python combat