时间:2021-07-01 10:21:17 帮助过:182人阅读
python可通过使用cx_Oracle模块对Oracle数据库进行操作。
首先,需要下载cx_Oracle模块,下载地址:https://pypi.python.org/pypi/cx_Oracle/6.0rc1
下载的时候注意版本,对照你所使用的Python版本和位数。
我所使用的是Python3.6,所以下载的版本是:cx_Oracle-6.0rc1-cp36-cp36m-win_amd64.whl
然后安装即可:
python -m pip install cx_Oracle-6.0rc1-cp36-cp36m-win_amd64.whl
代码举例:
#用途:操作oracle数据库demo
import cx_Oracle
user = "yzwxceshi"
passwd = "yzwxceshi"
listener = ‘192.168.20.191:1521/orcl‘
conn = cx_Oracle.connect(user, passwd, listener)
print(conn)
cursor = conn.cursor()
sql = "select * from T_MSIS_SM_ROLE"
#一次取一条数据,row为元组数据
cursor.execute(sql)
while (1):
row = cursor.fetchone()
if row == None:
break
print(row)
print("--------------------------------------")
#一次取所有数据,rows为元组列表数据
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
print(row)
#支持对数据库的插入、更新和删除操作。输入操作SQL,执行无返回。
def other_operation(sql):
cursor.execute(sql)
conn.commit()
print(sql)
cursor.close()
conn.close()
封装成类代码举例:
#oracle操作类
import cx_Oracle
class Oracle_Class:
user = "yzwxceshi"
passwd = "yzwxceshi"
listener = ‘192.168.20.191:1521/orcl‘
conn = cx_Oracle.connect(user, passwd, listener)
cursor = conn.cursor()
# 查询操作:一次性取所有数据。输入查询SQL,返回结果元组列表。
def querydata(self, sql):
list_result = []
self.cursor.execute(sql)
rows = self.cursor.fetchall()
for row in rows:
list_result.append(row)
return list_result
# 支持对数据库的插入、更新和删除操作。输入操作SQL,无返回。
def other_operation(self, sql):
self.cursor.execute(sql)
self.conn.commit()
print(sql)
# 关闭连接,释放资源
def close_all(self):
self.cursor.close()
self.conn.close()
调用代码:
#用于测试数据库操作 from oracle_class import Oracle_Class select_sql = "select ROLE_NAME from T_MSIS_SM_ROLE" insert_sql = "insert into T_MSIS_SM_ROLE values (14, ‘role_name‘, ‘普通用户‘)" update_sql = "update T_MSIS_SM_ROLE set ROLE_DESC = ‘测试用户‘ where ROLE_ID = 16" delete_sql = "delete from T_MSIS_SM_ROLE where ROLE_ID = 15" oracle_obj = Oracle_Class() oracle_obj.other_operation(delete_sql) list = oracle_obj.querydata(select_sql) print(list) oracle_obj.close_all()
python之Oracle操作(cx_Oracle)
标签:版本 exec rac 普通用户 comm com tar let imp