cx Oracle使用方法一

2022-08-24 07:21:10 字數 2878 閱讀 4975

正確安裝好cx_oracle之後,要使用它來連線到oracle資料庫進行操作,具體應該分3步走:

>>> import cx_oracle      # 匯入模組 

>>> db = cx_oracle.connect('hr', 'hrpwd', 'localhost:1521/xe') 建立連線,3 個引數分開寫

>>> db1 = cx_oracle.connect('hr/hrpwd@localhost:1521/xe') 建立連線,3 個引數連寫

>>> dsn_tns = cx_oracle.makedsn('localhost', 1521, 'xe')

>>> print dsn_tns

(description=(address_list=(address=(protocol=tcp)(host=localhost)(port=1521)))

(connect_data=(sid=xe)))

>>> db2 = cx_oracle.connect('hr', 'hrpwd', dsn_tns)

>>> print db.version

10.2.0.1.0

>>> versioning = db.version.split('.')

>>> print versioning

['10', '2', '0', '1', '0']

>>> if versioning[0]=='10':

... print "running 10g"

... elif versioning[0]=='9':

... print "running 9i"

...running 10g

>>> print db.dsn

localhost:1521/xe

>>>cursor = db.cursor() 建立乙個cursor

之後,我們可以呼叫這個cursor.execute(『sql『) 來執行sql語句。比如:

>>>cursor.execute(『select * from tabs』)

執行完畢以後,可以呼叫cursor.fetchall()一次取完所有結果,或者cursor.fetchone()一次取一行結果

>>>row=cursor.fetchall()

>>>for row in rows:

for v in row:

print v,

print

這樣就可以按照**的形式列印取得的結果了!

在從oracle取出資料的時候,考慮到它的資料型別了嗎?下面就是資料型別的對應表

帶引數的查詢:

>>> named_params = 

>>> query1 = cursor.execute('select * from employees where department_id=:dept_id and salary>:sal', named_params)

>>> query2 = cursor.execute('select * from employees where department_id=:dept_id and salary>:sal', dept_id=50, sal=1000)

這種是名字引數,還可以按位置引數:

r1 = cursor.execute('select * from locations where country_id=:1 and city=:2', ('us', 'seattle'))

注意:當只有一次引數的時候,也要把它寫成元組的形式,比如

cursor.execute(『select name from user where id=:1』,(login_id,))

千萬要注意,login_id後面還帶有乙個逗號!

cursor. prepare的用法,

這個方法就是在prepare之後,你再去execute的時候,就不用寫上sql語句引數了

>>> cursor.prepare('select * from jobs where min_salary>:min')

>>> r = cursor.execute(none, ) #注意,第乙個引數是none,

一次執行多條sql語句

>>> create_table = """

create table python_modules (

module_name varchar2(50) not null,

file_path varchar2(300) not null

)>>> from sys import modules

>>> cursor.execute(create_table)

>>> m =

>>> for m_name, m_info in modules.items():

... try:

... except attributeerror:

... pass

...>>> len(m)

76>>> cursor.prepare("insert into python_modules(module_name, file_path) values (:1, :2)")

>>> cursor.executemany(none, m)

>>> db.commit()

>>> r = cursor.execute("select count(*) from python_modules")

>>> print cursor.fetchone()

(76,)

>>> cursor.execute("drop table python_modules purge")

cx Oracle使用方法二

技術手冊 cx oracle使用方法 正確安裝好cx oracle之後,要使用它來連線到oracle資料庫進行操作,具體應該分3步走 import cx oracle 匯入模組 db cx oracle.connect hr hrpwd localhost 1521 xe 建立連線,3 個引數分開寫...

BMFont 使用方法 一

下面隨便找乙個字型庫 ttf 華文琥珀,字型樣板如下 開啟bmfont,1 字型設定 2 設定匯出引數 設定匯出大小,在此 設定為 512 64 畫素 設定文字效果 3 選擇需要匯出的文字 首先檢查是否有預設選擇的文字 如果有上圖那樣藍色的選項,說明有預設選擇的文字,清除所有預設選擇的文字 確保沒有...

使用 cx oracle連線oracle

1 各種軟體 oracle11g 服務端,客戶端 如果沒有簡易的install包也可以,cx oracle,還有python,注意版本一定要對應,2 安裝 安裝oracle服務端,客戶端 python 如果是windows,將客戶端bin目錄中的ocx.dll copy到python跟目錄 將x o...