RedHat 5.5 x86
Python 基礎語法參考:
Python 基礎語法知識
http://www.linuxidc.com/Linux/2011-04/34055.htm
一. cx_Oracle
Python 連接Oracle 數據庫,需要使用cx_Oracle 包。
該包的下載地址:http://cx-Oracle.sourceforge.net/
下載的時候,注意版本,對不同版本的Oracle 和平台,都有不同的cx_Oracle。
[root@rac1 u01]# rpm -ivh cx_Oracle-5.1-10g-py24-1.i386.rpm
Preparing... ########################################### [100%]
1:cx_Oracl ########################################### [100%]
Linux 平台下,用root 用戶進行安裝,並且還需要將一些Oracle 的環境變量添加到root用戶的.bash_profile 里。
最簡單的方法,就是直接把Oracle 用戶的變量copy過來:
PATH=$PATH:$HOME/bin
export Oracle_BASE=/u01/app/oracle
export Oracle_HOME=$ORACLE_BASE/product/10.2.0/db_1
export ORA_CRS_HOME=$Oracle_BASE/product/crs
export Oracle_SID=dave1
export PATH=.:${PATH}:$HOME/bin:$Oracle_HOME/bin:$ORA_CRS_HOME/bin
export PATH=${PATH}:/usr/bin:/bin:/usr/bin/X11:/usr/local/bin
export PATH=${PATH}:$Oracle_BASE/common/oracle/bin
export Oracle_TERM=xterm
export TNS_ADMIN=$Oracle_HOME/network/admin
export ORA_NLS10=$Oracle_HOME/nls/data
export LD_LIBRARY_PATH=$Oracle_HOME/lib
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$Oracle_HOME/oracm/lib
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/lib:/usr/lib:/usr/local/lib
export CLASSPATH=$Oracle_HOME/JRE
export CLASSPATH=${CLASSPATH}:$Oracle_HOME/jlib
export CLASSPATH=${CLASSPATH}:$Oracle_HOME/rdbms/jlib
export CLASSPATH=${CLASSPATH}:$Oracle_HOME/network/jlib
export THREADS_FLAG=native
export TEMP=/tmp
export TMPDIR=/tmp
然后source 應用一下。
二. Python 連Oracle 的基本操作
2.1 DB連接和關閉DB連接
2.1.1 方法一:用戶名,密碼和監聽 分開寫
[root@rac1 u01]# cat db.py
import cx_Oracle
db=cx_Oracle.connect('system','oracle','192.168.2.42:1521/dave')
print db.version
db.close()
[root@rac1 u01]# python db.py
10.2.0.1.0
2.1.2 方法二:用戶名,密碼和監聽寫在一起
[root@rac1 u01]# cat db.py
import cx_Oracle
db=cx_Oracle.connect('system/oracle@192.168.2.42:1521/dave')
print db.version
db.close()
[root@rac1 u01]# python db.py
10.2.0.1.0
2.1.3 方法三:配置監聽並連接
[root@rac1 u01]# cat db.py
import cx_Oracle
tns=cx_Oracle.makedsn('rac1',1521,'dave1')
db=cx_Oracle.connect('system','oracle',tns)
print tns
print db.version
vs=db.version.split('.')
print vs
if vs[0]=='10':
print "This is Oracle 10g!"
db.close()
[root@rac1 u01]# python db.py
(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=rac1)(PORT=1521)))(CONNECT_DATA=(SID=dave1)))
10.2.0.1.0
['10', '2', '0', '1', '0']
This is Oracle 10g!
2.2 建立cursor 並執行SQL語句
[root@rac1 u01]# cat db.py
import cx_Oracle
tns=cx_Oracle.makedsn('rac1',1521,'dave1')
db=cx_Oracle.connect('system','oracle',tns) --創建連接
cr=db.cursor() --創建cursor
sql='select * from phone'
cr.execute(sql) --執行sql 語句
print "\nThis is Fetchall!"
rs=cr.fetchall() --一次返回所有結果集
print "print all:(%s)" %rs
print "\n print by row:"
for x in rs:
print x
print "\nThis is Fetone!"
cr.execute(sql)
while(1):
rs=cr.fetchone() --一次返回一行
if rs ==None:break
print rs
--使用參數查詢
print "\n select with parameter:"
pr={'id':3,'tel':13888888888}
cr.execute('select * from phone where id=:id or phone=:tel',pr)
--這里我們將參數作為一個字典來處理的
rs=cr.fetchall()
print rs
cr.execute('select * from phone where id=:myid or phone=:myphone',myid=2,myphone=13888888888)
--這里我們直接寫參數
rs=cr.fetchall()
print rs
cr.close()
db.close()
[root@rac1 u01]# python db.py
This is Fetchall!
print all:([(1, 13865999999L), (2, 13888888888L)])
print by row:
(1, 13865999999L)
(2, 13888888888L)
This is Fetone!
(1, 13865999999L)
(2, 13888888888L)
select with parameter:
[(2, 13888888888L)]
[(2, 13888888888L)]
Python 類型和Oracle 類型的對應關系:
During the fetch stage, basic Oracle data types get mapped into their Python equivalents. cx_Oracle maintains a separate set of data types that helps in this transition. The Oracle - cx_Oracle - Python mappings are:
cx_Oracle |
Python |
|
VARCHAR2 |
cx_Oracle.STRING |
str |
CHAR |
cx_Oracle.FIXED_CHAR |
|
NUMBER |
cx_Oracle.NUMBER |
int |
FLOAT |
float |
|
DATE |
cx_Oracle.DATETIME |
datetime.datetime |
TIMESTAMP |
cx_Oracle.TIMESTAMP |
|
CLOB |
cx_Oracle.CLOB |
cx_Oracle.LOB |
三. 一個完成的示例
在這個例子里,我們將用Python 對DB 進行一些操作,包括,創建一張表,並插入一些數據,在修改其中的部分數據。
[root@rac1 u01]# cat dave.py
#!/usr/bin/python
#coding=utf-8
import cx_Oracle
import sys
import urllib
import os
def connectDB(dbname='dave'):
if dbname=='dave':
connstr='system/Oracle@192.168.2.42:1521/dave'
db=cx_Oracle.connect(connstr)
return db
def sqlSelect(sql,db):
#include:select
cr=db.cursor()
cr.execute(sql)
rs=cr.fetchall()
cr.close()
return rs
def sqlDML(sql,db):
#include: insert,update,delete
cr=db.cursor()
cr.execute(sql)
cr.close()
db.commit()
def sqlDML2(sql,params,db):
# execute dml with parameters
cr=db.cursor()
cr.execute(sql,params)
cr.close()
db.commit()
def sqlDDL(sql,db):
#include: create
cr=db.cursor()
cr.execute(sql)
cr.close()
if __name__=='__main__':
print "This is a test python program,write by tianlesoftware!\n"
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
#connect to database:
db=connectDB()
#create a table:
sql='create table dave(id number,name varchar2(20),phone number)'
sqlDDL(sql,db)
#insert data to table dave:
sql='insert into dave values(1,\'tianlesoftware\',13888888888)'
sqlDML(sql,db)
dt=[{'id':2,'name':'dave','phone':138888888888},
{'id':3,'name':'Oracle','phone':13888888888},
{'id':4,'name':'anqing','phone':13888888888}]
sql='insert into dave values(:id,:name,:phone)'
for x in dt:
sqlDML2(sql,x,db)
#select the result:
print "this is the first time select the data from dave"
sql='select * from dave'
rs=sqlSelect(sql,db)
for x in rs:
print x
#update data where id=1,change the name to anhui
sql='update dave set name=\'anhui\' where id=1'
sqlDML(sql,db)
#select again:
print "\n change the nanme to anhui where id equal 1,and select the result"
sql='select * from dave'
rs=sqlSelect(sql,db)
for x in rs:
print x
#delete data where id=3
sql='delete from dave where id=3'
sqlDML(sql,db)
#select again:
print "\n delete the data where id equal 3 and select the result"
sql='select * from dave'
rs=sqlSelect(sql,db)
for x in rs:
print x
db.close()
[root@rac1 u01]# python dave.py
This is a test python program,write by tianlesoftware!
this is the first time select the data from dave
(1, 'tianlesoftware', 13888888888L)
(2, 'dave', 138888888888L)
(3, 'Oracle', 13888888888L)
(4, 'anqing', 13888888888L)
change the nanme to anhui where id equal 1,and select the result
(1, 'anhui', 13888888888L)
(2, 'dave', 138888888888L)
(3, 'Oracle', 13888888888L)
(4, 'anqing', 13888888888L)
delete the data where id equal 3 and select the result
(1, 'anhui', 13888888888L)
(2, 'dave', 138888888888L)
(4, 'anqing', 13888888888L)
關於Python 連接Oracle 數據庫,及一些基本操作,就這么多。