Search code examples
pythondjangodatabase-connectionmysql-error-1064mysql-python

How to access a database in Django but without ORM support


I have a second database in my Django application, which is filled with static data about the equivalent of zipcodes in my country (Brazil) and the related streets, neighborhoods, cities and states.

I'm trying to access it like this:

from django.db import connections
from django.conf import settings

try:
    cursor = connections[settings.CEP_DATABASE_NAME].cursor()
    ....

but I get the following Error:

OperationalError: (1049, "Unknown database 'cep'")

My settings.py:

CEP_DATABASE_NAME = 'cep'
DATABASES = {
    'default': {
        'NAME': 'hypersaber',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST' : 'localhost',
        'PORT' : '3306',
        'OPTIONS' : {"init_command": "SET storage_engine=INNODB"}
    },
    CEP_DATABASE_NAME: {
        'NAME': CEP_DATABASE_NAME,
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST' : 'localhost',
        'PORT' : '3306',
        'OPTIONS' : {"init_command": "SET storage_engine=INNODB"}
    }
}

Both my MySQL DB instances are up and running.

Am I missing some configuration?

Thanks in advance.


Solution

  • Your code looks fine to me.

    I have to ask the obvious: Does that database actually exist on localhost?

    That's an exception thrown from the MySQLdb module, which makes me think there's nothing django-specific going wrong here and is why I ask if it's just a real, low-level error.

    Can you access the database from a regular (non django) python script?