0

I'm using Django to do some db query:

from django.db import connection

def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row

And below is my db settings:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ka_a',
        'USER': 'ka_a',
        'PASSWORD': 'ka_a',
        'HOST': 'xxx',
        'PORT': '3306',
        'STORAGE_ENGINE': 'INNODB',
        'OPTIONS': {
            'init_command': "set sql_mode='traditional'",
            'charset': 'utf8mb4'
        }
    },
    'ka_b': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ka_b',
        'USER': 'ka_b',
        'PASSWORD': 'ka_b',
        'HOST': 'xxxxx',
        'PORT': '3306',
        'STORAGE_ENGINE': 'INNODB',
    },
}

KA_B = 'ka_b'

How can I select to KA_B in connection?

Thanks

1 Answer 1

1

Found in doc:

If you need to access the DatabaseWrapper object itself, use connections[DEFAULT_DB_ALIAS] instead.

from django.db import connections

connection = connections[settings.KA_B]

with connection.cursor() as cursor:
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.