技术框架
开发语言:python,数据库:oracle,第三方库:cx_oracle(用于python和oracle的连接),prettytable(用于表格化输出展示数据)
开发步骤
一、安装cx_Oracle
pip install cx_Oracle
登录后复制
二、编写数据库操作类
直接使用了chatgpt提供的代码,因为我只用到了查询方法,所以只查没有增删改,另外考虑到要同时查询多次数据,所以自己修改了实现了一个连接池的功能。
import cx_Oracleimport queueclass OracleDatabase: # 构造函数,传入数据库连接参数 def __init__(self, user, pwd, dsn, size): self.user = user self.pwd = pwd self.dsn = dsn ## 定义连接池 self.size = size self.conn_queue = queue.Queue(maxsize=self.size) for i in range(self.size): self.conn_queue.put(self._create_connection()) # 创建数据库连接 def _create_connection(self): return cx_Oracle.connect(self.user, self.pwd, self.dsn) # 从连接池里面获取连接 def _get_conn(self): conn = self.conn_queue.get() if conn is None: self._create_connection() return conn # 将连接put到连接池中 def _put_conn(self, conn): self.conn_queue.put(conn) # 关闭所有连接 def _close_conn(self): try: while True: conn = self.conn_queue.get_nowait() if conn: conn.close() except queue.Empty: print(">>>>数据库连接全部关闭三、输入订单号,执行查询
if __name__ == '__main__': user = "user_dba" pwd = "user_password" dsn = cx_Oracle.makedsn('0.0.0.0', '1521', service_name='s_demo_db') db = OracleDatabase(user, pwd, dsn, 2) cl_code = input("输入订单号: ").strip() print("数据信息展示:") sql_1 = """select * from table_demo c where c.cl_code = :cl_code""" results_1 = db.query(sql_1, [cl_code])print(results_1)# ......登录后复制
四、格式化打印
安装prettytable
pip install PrettyTable登录后复制
示例代码
from prettytable import PrettyTable## 接着第三部分的代码tb_1 = PrettyTable(['**号', '**时间', '当前状态', '单号', '机构'])for rs_1 in results_1:tb_1.add_row([rs_1[0], rs_1[1], rs_1[2], rs_1[3], rs_1[4]])print(tb_1)登录后复制
五、打印效果
使用效果如下:粘贴订单号回车,直接返回下面所需要的信息数据(测试数据):
立即学习“Python免费学习笔记(深入)”;
问题记录
第一个问题就是安装 cx_Oracle的时候出错:
ERROR: Could not build wheels for cx_Oracle, which is required to install pyproject.toml-based projects
解决方式:安装Microsoft C++ 生成工具,Microsoft C++ 生成工具 - Visual Studio,更改安装目录,按照默认选项安装即可。
报错信息
cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library:"The specified module could not be found".See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help
解决方式:复制oracle客户端(客户端下载见问题3)目录中的oci,oraocci11,oraociei11的3个DLL粘贴到你的Paython目录的Lib/site-packages文件夹下面。
报错信息
cx_Oracle.DatabaseError: DPI-1072: the Oracle Client library version is unsupported
下载oracle客户端,并解压安装。下载地址:oracle.github.io/odpi/doc/installation 我出现这个问题,是因为我本机原来安装的是19.18版本,换成11.2版本的客户端,按照问题2的操作,将三个dll文件重新复制过去,解决问题。
后期优化
将sql语句集中放到配置文件里面,并配置表头,可以实现多查询自由扩展。
通过bat脚本调用执行,真正实现一键查询。
以上就是Python连接oracle的问题怎么解决的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2239034.html