Search code examples
mysqldjangoorm

Connecting to django mysql without specifying database/schema


In normal circumstances, you run mysql -h and if you can connect to db as current user, you are in. Then you can select database and other operations.

Now we move to django context.

We do connection.cursor() but it defaults to database you specify in settings. As it happens it may or may not be yet created. But you know db is there and you want to perform some checks and whatnot.

How to do it?


Solution

  • I dived deep into Django and actually found a solution:

    Django <= 3.0

    with connection._nodb_connection.cursor() as cursor:
        cursor.execute("SHOW databases")
        rows = cursor.fetchall()
    

    Django >= 3.1

    with connection._nodb_cursor() as cursor:
        cursor.execute("SHOW databases")
        rows = cursor.fetchall()
    

    Here you have it!