You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle 11g环境下Python脚本查询客户邮箱并发送文件问题求助

针对Oracle 11g环境的脚本修复方案

你的脚本在Oracle 11g下运行失败,核心原因是oracledb默认的Thin驱动模式不完全兼容Oracle 11g,再加上部分配置和数据类型匹配问题。以下是具体排查和修复步骤:

1. 切换到Thick驱动模式

Oracle 11g不支持oracledb Thin模式的全部特性,必须启用Thick模式(依赖Oracle客户端库)。先确保安装了Oracle 12c或更高版本的客户端(11g客户端与新版oracledb兼容性极差),再修改代码初始化Thick模式:

import re
import oracledb

# 初始化Thick模式,指定Oracle客户端bin目录路径
oracledb.init_oracle_client(lib_dir="C:/app/client/name/product/12.2.0/client_1/bin")

# Database connection details
db_username = "username"
db_password = "password"
db_dsn = "mis"

# Regular expression pattern to extract customer number from filenames
filename_pattern = r"COD_(\d+)\.pdf"

def extract_customer_number(filename):
    match = re.search(filename_pattern, filename)
    if match:
        return match.group(1)
    return None

def get_customer_email_from_database(customer_number):
    try:
        # Thick模式无需config_dir参数,依赖客户端tnsnames.ora配置
        connection = oracledb.connect(user=db_username, password=db_password, dsn=db_dsn)
        cursor = connection.cursor()

        # 若数据库中cus_no为数字类型,将字符串编号转为整数避免隐式转换错误
        query = "SELECT t.int_addr FROM mis_customer t WHERE t.cus_no = :c_number"
        result = cursor.execute(query, c_number=int(customer_number)).fetchone()

        cursor.close()
        connection.close()

        if result:
            return result[0]
        else:
            return None

    except oracledb.DatabaseError as e:
        error, = e.args
        raise Exception(f"数据库错误: {error.message}, 错误代码: {error.code}")

# Example filename
filename = "COD_044916.pdf"

try:
    # Extract customer number from filename
    customer_number = extract_customer_number(filename)
    if customer_number:
        # Retrieve customer email from the database
        customer_email = get_customer_email_from_database(customer_number)
        if customer_email:
            print(f"客户编号: {customer_number}")
            print(f"客户邮箱: {customer_email}")
        else:
            print(f"数据库中未找到编号为{customer_number}的客户。")
    else:
        print("文件名不符合预期格式。")

except Exception as e:
    print(f"发生错误: {e}")

2. 关键修改点说明

  • 启用Thick模式:通过oracledb.init_oracle_client()指定Oracle客户端的bin目录,确保Python能正确加载客户端库,Windows环境注意路径分隔符用/或双反斜杠\\。
  • 移除config_dir参数:Thick模式依赖客户端的tnsnames.ora配置文件,无需在connect方法中额外指定。
  • 数据类型匹配:如果数据库表mis_customer的cus_no是数字类型(NUMBER/INTEGER),将提取的字符串类型客户编号转为整数,避免Oracle隐式转换引发的性能问题或匹配失败。
  • 优化错误信息:解析oracledb.DatabaseError的具体错误代码和消息,方便快速定位连接或SQL执行问题。

3. 额外环境检查

  • 确保Oracle客户端的bin目录已添加到系统环境变量PATH(Windows)或LD_LIBRARY_PATH(Linux),避免库加载失败。
  • 验证tnsnames.ora中的mis服务名配置正确,能正常连接到Oracle 11g实例。
  • 确认数据库用户username拥有mis_customer表的查询权限。

内容的提问来源于stack exchange,提问作者Michael Benning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:11:20