1. 要想使Python可以操作Oracle數(shù)據(jù)庫,首先需要安裝cx_Oracle包,可以通過下面的地址來獲取安裝包
[plain]
1.http://cx-Oracle.sourceforge.net/
2. 另外還需要Oracle的一些類庫,此時需要在運行python的機器上安裝Oracle Instant Client軟件包,可以通過下面地址獲得-
[plain]
1.http://www.Oracle.com/technetwork/database/features/instant-client/index-097480.html
找到符合自己平臺的包,然后安裝,這里我使用的是rpm包,所以使用以下命令安裝
[plain]
1.$ sudo rpm -ivh Oracle-instantclient11.2-basic-11.2.0.3.0-1.i386.rpm
裝完畢后還需要設置一下環(huán)境變量,如下
[plain]
1.$ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/lib/Oracle/11.2/client/lib
3. 創(chuàng)建一個簡單的python文件,測試安裝是否成功
[python]
1.import cx_Oracle
2.
3.conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl') 4.cursor = conn.cursor ()
5.cursor.execute ("select * from dual") 6.row = cursor.fetchone ()
7.print row[0] 8.
9.cursor.close ()
10.conn.close ()
4. 下面看一個數(shù)據(jù)庫建表和插入操作
[python]
1.import cx_Oracle
2.
3.conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl') 4.cursor = conn.cursor ()
5.
6.cursor.execute ("CREATE TABLE TEST(ID INT, COL1 VARCHAR(32), COL2 VARCHAR(32), COL3 VARCHAR(32))") 7.
8.cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(1, 'a', 'b', 'c')") 9.cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(2, 'aa', 'bb', 'cc')") 10.cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(3, 'aaa', 'bbb', 'ccc')") 11.conn.commit()
12.
13.cursor.close ()
14.conn.close ()
5. 下面再來看看查詢,查詢通常有兩種方式:一種是使用cursor.fetchall()獲取所有查詢結(jié)果,然后再一行一行的迭代;另一種每次通過cursor.fetchone()獲取一條記錄,直到獲取的結(jié)果為空為止?匆幌孪旅娴睦樱
[python]
1.import cx_Oracle
2.
3.conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl') 4.cursor = conn.cursor ()
5.
6.cursor.execute ("SELECT * FROM TEST") 7.rows = cursor.fetchall()
8.for row in rows: 9. print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) 10.
11.print "Number of rows returned: %d" % cursor.rowcount 12.
13.cursor.execute ("SELECT * FROM TEST") 14.while (1): 15. row = cursor.fetchone()
16. if row == None: 17. break 18. print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]) 19.
20.print "Number of rows returned: %d" % cursor.rowcount 21.
22.cursor.close ()
23.conn.close ()
本文出自:億恩科技【1tcdy.com】
服務器租用/服務器托管中國五強!虛擬主機域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|