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

如何通过django.db对象调用oracledb connection的gettype()方法?

问题描述

我有一个基于Oracle数据库的小型Django应用,使用版本为Django 5.0.3和oracledb 2.0.1。oracledb库的原生Connection对象提供了gettype()方法,用于获取数据库自定义类型,但尝试通过django.db提供的connection对象调用该方法时失败。

数据库配置(settings.py):

import oracledb
from pathlib import Path

# Database
d = r"/path/to/oracle/instantclient"
oracledb.init_oracle_client(lib_dir=d)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': '<db-name>',
        'USER': '<db-user>',
        'PASSWORD': '<db-password>',
    }
}

尝试的代码:

from django.db import connection

def myfunc():
    with connection.cursor() as c:
        c.execute("select * from v$version")
        rows = c.fetchall()
        print(rows)

    my_db_type = connection.gettype("MY_DB_TYPE")

报错信息:

[('Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production', 'Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 
- Production\nVersion 19.23.0.1.0', 'Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production', 0)]
ERROR:root:global error:
ERROR:root:global Exception type: AttributeError
ERROR:root:global Exception message: 'DatabaseWrapper' object has no attribute 'gettype'
解决方案

django.db导出的connection是Django封装的DatabaseWrapper对象,并非oracledb的原生Connection实例,因此直接调用gettype()会报错。要调用oracledb原生方法,需要获取底层的原生连接对象:

  1. 获取原生连接:通过DatabaseWrapper的connection属性可以拿到oracledb的原生Connection实例,但要确保此时数据库连接已经建立(比如在cursor上下文内,或者手动触发连接)。

  2. 修改后的示例代码:

from django.db import connection

def myfunc():
    with connection.cursor() as c:
        c.execute("select * from v$version")
        rows = c.fetchall()
        print(rows)
        
        # 获取oracledb原生连接
        native_conn = connection.connection
        # 调用gettype方法
        my_db_type = native_conn.gettype("MY_DB_TYPE")
        print(my_db_type)

如果不在cursor上下文内,需要先确保连接已建立:

from django.db import connection

def myfunc():
    # 手动建立连接(如果尚未连接)
    if not connection.connection:
        connection.connect()
    
    native_conn = connection.connection
    my_db_type = native_conn.gettype("MY_DB_TYPE")
注意事项
  • 原生连接对象的生命周期由Django管理,不要手动关闭它,否则会导致Django后续数据库操作出错。
  • 确保在调用原生方法时,连接处于活跃状态,避免因连接被回收而引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:03:15