第一步:导入cx_Oracle ,建立连接
复制代码

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 光标

复制代码

cursor = db.cursor()

建立一个cursor之后,我们可以调用这个cursor.execute(‘SQL‘) 来执行SQL语句。比如:

cursor.execute(‘select * from tabs’)

执行完毕以后,可以调用cursor.fetchall()一次取完所有结果,或者cursor.fetchone()一次取一行结果

row=cursor.fetchall()
for x in row:
For y in x:
Print y,
Print

复制代码
这样就可以按照表格的形式打印取得的结果了!
在从oracle取出数据的时候,考虑到它的数据类型了吗?下面就是数据类型的对应表
Datatypes
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:

Oracle cx_Oracle Python
VARCHAR2
NVARCHAR2
LONG 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

BLOB cx_Oracle.BLOB

带参数的查询:

named_params = {‘dept_id’:50, ‘sal’:1000}
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, {‘min’:1000}) #注意,第一个参数是None
一次执行多条sql语句:
Large insert operations don’t require many separate inserts because Python fully supports inserting many rows at once with the cx_Oracle.Cursor.executemany method. Limiting the number of execute operations improves program performance a lot and should be the first thing to think about when writing applications heavy on INSERTs.
Let’s create a table for a Python module list, this time directly from Python. You will drop it later.
复制代码
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:
… M.append((m_name, m_info.file))
… 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”)

复制代码
BLOB & CLOB 格式的创建:

binary_content = cursor.var(cx_Oracle.BLOB)
binary_content.setvalue(0, content)


第一步:导入cx_Oracle ,建立连接

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 光标
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 = {‘dept_id’:50, ‘sal’:1000}
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, {‘min’:1000}) #注意,第一个参数是None,
一次执行多条sql语句

Large insert operations don’t require many separate inserts because Python fully supports inserting many rows at once with the cx_Oracle.Cursor.executemany method. Limiting the number of execute operations improves program performance a lot and should be the first thing to think about when writing applications heavy on INSERTs.
Let’s create a table for a Python module list, this time directly from Python. You will drop it later.

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:
… M.append((m_name, m_info.file))
… 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”)

  1. 创建一个简单的python文件,测试安装是否成功
    import cx_Oracle

conn = cx_Oracle.connect(‘fkong/fkong@172.17.23.129/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/fkong@172.17.23.129/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/fkong@172.17.23.129/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 ()

cx_Oracle使用方法相关推荐

  1. 【转】python 和 cx_Oracle 的使用

    下载地址: http://sourceforge.net/projects/cx-oracle/?source=directory(失效的话请自己百度)下载的时候注意数据库版本和操作系统环境. 技术手 ...

  2. MacOS系统安装cx_Oracle

    文章目录 一. 原理介绍: 二.安装环境 三.准备软件包 3.1 oracle_client和SDK 3.2 cx_Oracle 四.安装步骤 4.1 解压oracle_client ,SDK软件包. ...

  3. python访问数据库如何解决高并发_使用 Python 和 Oracle 数据库实现高并发性

    随着趋势发展的核心转向更多而不是更快发展,最大限度地提高并发性的重要性日益凸显.并发性使得编程模式发生了新的转变,可以编写异步代码,从而将多个任务分散到一组线程或进程中并行工作.如果您不是编程新手并且 ...

  4. linux系统如何创建python文件_Linux搭建python环境详解

    一.下载文件 版本:setuptools-0.6c11 版本:pip-1.5.6.tar.gz 版本:pymongo-2.7.2.tar.gz 版本:xlrd-0.9.3.tar.gz 版本:xlwt ...

  5. UI自动化测试环境搭建 Python+Selenium+RobotFramework

    UI自动化测试环境准备&RF框架的机制 一.流程与模块介绍 web自动化测试主要有四个部分组成,分别是数据源.自动化脚本.驱动程序.浏览器四个部分.数据源指的就是前端web页面数据的来源,MY ...

  6. 在 Oracle Enterprise Linux 和 iSCSI 上构建您自己的 Oracle RAC 11g 集群

    作者:Jeffrey Hunter 了解如何以低于 2,700 美元的费用在 Oracle Enterprise Linux 上安装并配置 Oracle RAC 11g 第 2 版开发集群. 本指南中 ...

  7. Java面试题大全2021版

    一.Java 基础 JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境. JRE:Java Run ...

  8. python cx_oracle 有超时的设置吗_python cx_Oracle的基础使用方法(连接和增删改查)

    问题 使用python操作oracle数据库,获取表的某几个字段作为变量值使用. 使用Popen+sqlplus的方法需要对格式进行控制,通过流获取这几个字段值不简洁(个人观点--).(优点是能够使用 ...

  9. python安装cv-oracle时如何解决vc++的问题_python中cx_Oracle模块安装遇到的问题与解决方法...

    --=========================================================================== 我的实践过程: 1,将oci.dll文件(从 ...

最新文章

  1. [UML]UML系列——状态机图statechart diagram
  2. 我爱的人,你知道我一直在
  3. linux变量赋值取值,linuxshell编程对变量的赋值
  4. xml转换为json格式时,如何将指定节点转换成数组 Json.NET
  5. 面试官:Spring代理目标bean时为何通过TargetSource类型对目标bean封装?
  6. EAS 表格、查询方案存储表
  7. [tf] config.gpu_options.allow_growth=True
  8. Mysql查询按照某字段指定顺序排序
  9. 创建型模式专题总结:Creational Pattern(转自Terrylee)
  10. 把Sublime添加到Mac右键菜单
  11. QQ群发精灵V3.2
  12. Beautifulsoup+正则表达式多线程爬取小姐姐图片
  13. 配置pcl(点云)环境遇到的问题(华南理工大学三维人体建模与测量)
  14. Python实现中文转拼音功能
  15. Day3 4月29日
  16. DSOX2022A示波器的使用
  17. 北航计算机在职研究生多少钱,在职攻读北航研究生需要多少学费?
  18. R统计绘图-factoextra包绘制PCA图
  19. John the Ripper编译安装及使用
  20. 三件事看优酷关于视频网站版权的问题

热门文章

  1. 移动直播进入下半场盈利为王,突破打赏模式成关键
  2. Flink 入门实战之一HelloWord
  3. [从头读历史] 第252节 春秋时期各诸侯国的地域分布
  4. 视频编码技术 -1.2色彩原理
  5. lcd屏和amoled屏的优缺点 lcd屏和amoled屏哪个效果好
  6. AMA专题: 深入解读Read2N三大创新, 全面启动市场引擎
  7. 计算机被老师关闭网络了,电脑被老师控制如何解控
  8. UVa Online Judge 西班牙Valladolid 在线判官 和 uDebug使用简单教程
  9. 世上最小的卡片电脑 RaspberrysPi Zero W 入手体验
  10. 双官能交联剂点击试剂DBCO-PEG4-DBCO