1. 程式人生 > >Python實戰之Oracle資料庫操作

Python實戰之Oracle資料庫操作

本文地址:http://blog.csdn.net/kongxx/article/details/7107661

1. 要想使Python可以操作Oracle資料庫,首先需要安裝cx_Oracle包,可以通過下面的地址來獲取安裝包

http://cx-oracle.sourceforge.net/
2. 另外還需要oracle的一些類庫,此時需要在執行python的機器上安裝Oracle Instant Client軟體包,可以通過下面地址獲得
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
找到符合自己平臺的包,然後安裝,這裡我使用的是rpm包,所以使用以下命令安裝
$ sudo rpm -ivh  oracle-instantclient11.2-basic-11.2.0.3.0-1.i386.rpm
裝完畢後還需要設定一下環境變數,如下
$ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/lib/oracle/11.2/client/lib
3. 建立一個簡單的python檔案,測試安裝是否成功
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. 下面看一個數據庫建表和插入操作
import cx_Oracle

conn = cx_Oracle.connect('fkong/[email protected]/orcl')  
cursor = conn.cursor ()

cursor.execute ("CREATE TABLE TEST(ID INT, COL1 VARCHAR(32), COL2 VARCHAR(32), COL3 VARCHAR(32))")

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. 下面再來看看查詢,查詢通常有兩種方式:一種是使用cursor.fetchall()獲取所有查詢結果,然後再一行一行的迭代;另一種每次通過cursor.fetchone()獲取一條記錄,直到獲取的結果為空為止。看一下下面的例子:
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 ()