介绍了基本使用,本文介绍一下使用python 对oracle 数据库进行常见操作的介绍
oracle@rac3:/home/oracle/python>cat sqlops.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cx_oracle
import sys
import urllib
import os
# function #
def conndb(dbname='yangdb',username='yang',pwd='yang'):
<b>##创建数据库连接,设置默认值 </b>
if dbname == 'yangdb':
username = "yang"
pwd = "yang"
dsn=cx_oracle.makedsn('127.0.0.1','1523','yangdb')
db=cx_oracle.connect(username,pwd,dsn)
return db
def selectdb(db,sql):
<b>##select 查询</b>
cursor = db.cursor()
cursor.execute(sql)
result=cursor.fetchall()
cursor.close()
return result
def dmldb_n(db,sql):
<b>##插入,更新,删除</b>
cursor = db.cursor()
cursor.execute(sql)
cursor.close()
db.commit()
def dmldb_p(db,sql,para):
cursor.execute(sql,para)
def ddldb(db,sql):
<b>#ddl 语句</b>
cursor=db.cursor()
def printresult(rs):
for row in rs:
print row
print "============== 连接数据库 =================="
db=conndb()
print "===============创建表 pytb=================="
ddl='create table pytab(id number,val varchar2(20))'
ddldb(db,ddl)
sel='select * from pytab'
rs=selectdb(db,sel)
printresult(rs)
print "===============向pytb插入数据==============="
inst='insert into pytab values(0,\'dba\')'
dmldb_n(db,inst)
print "=======使用参数,向pytb插入数据============="
dt=[{'id':1,'val':'qilong'},
{'id':2,'val':'xxq'},
{'id':3,'val':'aliyun'},
{'id':4,'val':'aliyundba'},
{'id':5,'val':'aliyunsa'},
{'id':6,'val':'aliyunidc'},
{'id':7,'val':'aliyunnework'},
{'id':8,'val':'alibaba'},
{'id':9,'val':'taobao'},
{'id':10,'val':'alipay'},
{'id':11,'val':'tech'},
{'id':12,'val':'oracle'},
{'id':13,'val':'ibm'}
]
inst='insert into pytab values(:id,:val)'
for bulk in dt:
dmldb_p(db,inst,bulk)
print "===============删除表 pytb 数据=============="
delt='delete from pytab where id=1'
dmldb_n(db,delt)
print "===============查询表 pytb 数据=============="
<b>结果显示:</b>
oracle@rac3:/home/oracle/python>python sqlops.py
============== 连接数据库 ==================
===============创建表 pytb==================
===============向pytb插入数据===============
(0, 'dba')
=======使用参数,向pytb插入数据=============
(1, 'qilong')
(2, 'xxq')
(3, 'aliyun')
(4, 'aliyundba')
(5, 'aliyunsa')
(6, 'aliyunidc')
(7, 'aliyunnework')
(8, 'alibaba')
(9, 'taobao')
(10, 'alipay')
(11, 'tech')
(12, 'oracle')
(13, 'ibm')
===============删除表 pytb 数据==============
===============查询表 pytb 数据==============