如何在 Django 中创建新的数据库连接 [英] How to create new database connection in django

查看:57
本文介绍了如何在 Django 中创建新的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个新的数据库连接(会话)以避免在我的 Django 事务中来自 MySql 过程的意外提交.如何在 django 中设置?

I need to create a new database connection(session) to avoid an unexpected commit from a MySql procedure in my django transaction. How to set up it in django?

我试图复制设置文件中的数据库配置.它对我有用,但似乎不是一个好的解决方案.查看我的代码了解更多详情.

I have tried to duplicate the database configuration in setting file. It worked for me but it seems not a good solution. See my code for more detail.

@classmethod
def get_sequence_no(cls, name='', enable_transaction=False):
    """
        return the sequence no for the given key name
    """
    if enable_transaction:
        valobj = cls.objects.using('sequence_no').raw("call sp_get_next_id('%s')" % name)
        return valobj[0].current_val
    else:
        valobj = cls.objects.raw("call sp_get_next_id('%s')" % name)
        return valobj[0].current_val

有谁知道如何使用自定义数据库连接来调用程序?

Does anyone know how to use a custom database connection to call the procedure?

推荐答案

如果你看一下 django.db 模块,你可以看到 django.db.connectiondjango.db.connections[DEFAULT_DB_ALIAS] 的代理,django.db.connectionsdjango.db.utils.ConnectionHandler 的一个实例代码>.

If you have a look at the django.db module, you can see that django.db.connection is a proxy for django.db.connections[DEFAULT_DB_ALIAS] and django.db.connections is an instance of django.db.utils.ConnectionHandler.

把这些放在一起,你应该能够像这样获得一个新的连接:

Putting this together, you should be able to get a new connection like this:

from django.db import connections
from django.db.utils import DEFAULT_DB_ALIAS, load_backend
    

def create_connection(alias=DEFAULT_DB_ALIAS):
    connections.ensure_defaults(alias)
    connections.prepare_test_settings(alias)
    db = connections.databases[alias]
    backend = load_backend(db['ENGINE'])
    return backend.DatabaseWrapper(db, alias)

注意这个函数每次被调用都会打开一个新的连接,你负责关闭它.此外,它使用的 API 可能被认为是内部的,可能会在不通知的情况下发生变化.

Note that this function will open a new connection every time it is called and you are responsible for closing it. Also, the APIs it uses are probably considered internal and might change without notice.

要关闭连接,在 create_connection 函数返回的对象上调用 .close() 应该就足够了:

To close the connection, it should be enough to call .close() on the object return by the create_connection function:

conn = create_connection()
# do some stuff
conn.close()

这篇关于如何在 Django 中创建新的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆