Python實戰之Oracle資料庫操作

來源:互聯網
上載者:User

本文地址: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/lib3. 建立一個簡單的python檔案,測試安裝是否成功import cx_Oracle</p><p>conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')<br />cursor = conn.cursor ()<br />cursor.execute ("select * from dual")<br />row = cursor.fetchone ()<br />print row[0]</p><p>cursor.close ()<br />conn.close ()4. 下面看一個資料庫建表和插入操作import cx_Oracle</p><p>conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')<br />cursor = conn.cursor ()</p><p>cursor.execute ("CREATE TABLE TEST(ID INT, COL1 VARCHAR(32), COL2 VARCHAR(32), COL3 VARCHAR(32))")</p><p>cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(1, 'a', 'b', 'c')")<br />cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(2, 'aa', 'bb', 'cc')")<br />cursor.execute ("INSERT INTO TEST (ID, COL1, COL2, COL3)VALUES(3, 'aaa', 'bbb', 'ccc')")<br />conn.commit()</p><p>cursor.close ()<br />conn.close ()5. 下面再來看看查詢,查詢通常有兩種方式:一種是使用cursor.fetchall()擷取所有查詢結果,然後再一行一行的迭代;另一種每次通過cursor.fetchone()擷取一條記錄,直到擷取的結果為空白為止。看一下下面的例子:import cx_Oracle</p><p>conn = cx_Oracle.connect('fkong/fkong@172.17.23.129/orcl')<br />cursor = conn.cursor ()</p><p>cursor.execute ("SELECT * FROM TEST")<br />rows = cursor.fetchall()<br />for row in rows:<br />print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])</p><p>print "Number of rows returned: %d" % cursor.rowcount</p><p>cursor.execute ("SELECT * FROM TEST")<br />while (1):<br />row = cursor.fetchone()<br />if row == None:<br />break<br />print "%d, %s, %s, %s" % (row[0], row[1], row[2], row[3])</p><p>print "Number of rows returned: %d" % cursor.rowcount</p><p>cursor.close ()<br />conn.close ()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.