博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Using Python With Oracle Database 11g 精简版
阅读量:6853 次
发布时间:2019-06-26

本文共 5701 字,大约阅读时间需要 19 分钟。

  hot3.png

www.oracle.com/technetwork/cn/server-storage/linux/python-091105.html

Connecting to Oracle

import cx_Oraclecon = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl')print con.versioncon.close()

Using Database Resident Connection Pooling

Below left is diagram of nonpooling. Every script has its own database server proces. Scripts not doing any database work still hold onto a connection until the connection is closed and the server is terminated. Below right is a diagram with DRCP. Scripts can use database servers from a pool of servers and return them when no longer needed.

114052_6myF_2254888.gif

114053_LsZk_2254888.gif

con = cx_Oracle.connect('pythonhol', 'welcome', '127.0.0.1:/orcl:pooled',             cclass = "HOL", purity = cx_Oracle.ATTR_PURITY_SELF)

This is similar to connect.py but ":pooled" is appended to the connection string. A Connection Class "HOL" is also passed into the connect() method and the "purity" of the connection is defined as the ATTR_PURITY_SELF constant.

Creating a Simple Query

cur = con.cursor()cur.execute('select * from departments order by department_id')for result in cur:    print resultcur.close()

The cursor() method opens a cursor for statements to use. The execute() method parses and executes the statement.

Fetching Data

row = cur.fetchone()print rowrow = cur.fetchone()print row

This uses the fetchone() method to return just a single row as a tuple.

res = cur.fetchmany(numRows=3)

Here the numRows parameter specifices that three rows should be returned.

res = cur.fetchall()

This uses the fetchall() method to return all rows. The output is a list (Python's name for an array) of tuples.

Improve Query Performance

import time

import cx_Oraclecon = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl')start = time.time()cur = con.cursor()cur.arraysize = 100cur.execute('select * from bigtab')  #table bigtab is a table with a large number of rowsres = cur.fetchall()# print res  # uncomment to display the query resultselapsed = (time.time() - start)print elapsed, " seconds"cur.close()con.close()

The default arraysize used by cx_Oracle is 50. In general, larger array sizes improve performance.

Using Bind Variables

cur.prepare('select * from departments where department_id = :id')cur.execute(None, {'id': 210})cur.execute(None, {'id': 110})

The special symbol 'None' is used in place of the statement text argument to execute() because the prepare() method has already set the statement. The statement contains a bind variable ":id".

rows = [ (1, "First" ), (2, "Second" ), (3, "Third" ),(4, "Fourth" ), (5, "Fifth" ), (6, "Sixth" ),(7, "Seventh" ) ]cur.bindarraysize = 7cur.setinputsizes(int, 20)cur.executemany("insert into mytab(id, data) values (:1, :2)", rows)#con.commit()

The bindarraysize is here set to 7, meaning to insert all seven rows in one step. The setinputsizes() call describes the columns. The first column is integral. The second column has a maximum of 20 bytes.The executemany() call inserts all seven rows.

Creating Transactions

con.commit()con.close()

The commit() is on the connection. When the changed data is committed to the database, it is then available to other users and sessions.

Rerun the script several times and see the number of rows in the table increasing each time:

114317_rKei_2254888.gif

If you need to initiate a rollback in a script, the con.rollback() method can be used.

Using PL/SQL Stored Functions and Procedures

set echo oncreate or replace functionmyfunc(d_p in varchar2, i_p in number) return number asbegin  insert into ptab (mydata, myid) values (d_p, i_p);  return (i_p * 2);end;

creates a PL/SQL stored function myfunc() to insert a row into the ptab table, and return double the inserted value.

res = cur.callfunc('myfunc', cx_Oracle.NUMBER, ('abc', 2))

This uses callfunc() to execute the function. The constant cx_oracle.NUMBER indicates that the return value is numeric. The two PL/SQL function parameters are passed as a tuple and bound to the function parameter arguments.

To call a PL/SQL procedure, use the cur.callproc() method.

set echo oncreate or replace proceduremyproc(v1_p in number, v2_p out number) asbegin   v2_p := v1_p * 2;end;

This creates a numeric variable myvar to hold the OUT parameter. The number 123 and the return variable name are bound to the procedure call parameters using a tuple.

myvar = cur.var(cx_Oracle.NUMBER)cur.callproc('myproc', (123, myvar))print myvar.getvalue()

Continuous Query Notification

import cx_Oracledef DCNCallback(message):    print "Notification:"    for tab in message.tables:        print "Table:", tab.name        for row in tab.rows:            if row.operation & cx_Oracle.OPCODE_INSERT:                print "INSERT of rowid:", row.rowid            if row.operation & cx_Oracle.OPCODE_DELETE:                print "DELETE of rowid:", row.rowid

This script creates a function called DCNCallback(). This function will be called when a table changes. The 'message' parameter is a cx_Oracle object that will contain information about the changes.

con = cx_Oracle.Connection("pythonhol/welcome@127.0.0.1/orcl",events = True)subscriptionInsDel = con.subscribe(callback = DCNCallback,             operations = cx_Oracle.OPCODE_INSERT | cx_Oracle.OPCODE_DELETE,rowids = True)subscriptionInsDel.registerquery('select * from mytab')raw_input("Hit Enter to conclude this demo\n")

The subscribe() call registers the DCNCallback() to be called in a new thread when an INSERT or 

UPDATE occurs. 

The registerquery() call registers a query that selects everything from the MYTAB table. Any change to the table that is an UPDATE or DELETE will cause DCNCallback() to be called. 

The script concludes with a raw_input() call that waits for user input before terminating.

转载于:https://my.oschina.net/xcxt/blog/397262

你可能感兴趣的文章
有关微刊的一些想法
查看>>
Windows2003 RIS 通过网络安装系统
查看>>
Java学习日志(24-1-网络编程-自定义服务端与客户端)
查看>>
Hibernate笔记——8.关联映射(中)
查看>>
杀掉linux下的僵尸进程
查看>>
开源协定
查看>>
簡介SCST
查看>>
HAZELCAST 客户端命令 可用于简单调试
查看>>
我的友情链接
查看>>
iframe自动调整大小
查看>>
用局域网文件共享系统实现共享文件夹安全设置
查看>>
DropWizard:用Java轻轻的写一个RESTful Service
查看>>
文件合并工具DiffMerge发布4.2版本
查看>>
接口测试基础
查看>>
jquery动态添加删除tr
查看>>
JSP内置对象映射表
查看>>
RadixSort -- 基数排序
查看>>
分享21个最新的超酷web设计特效
查看>>
jQuery中 wrap() wrapAll() 与 wrapInner()的区别
查看>>
wc命令
查看>>