Django doesn't use pyodbc as python does

I have a python script using pyodbc to read a 2005 sql server database:

import pyodbc
con = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=schema;UID=user;PWD=pass')
cursor = con.cursor()
cursor.execute(str.format("SELECT id FROM schema.dbo.mytable WHERE num = {0}", foo.num)

This works fine.

When I try to configure a database in my django project settings with the same parameters, I can't read tables from the same database.

'second_db': {
        'ENGINE': 'sql_server.pyodbc',
        'NAME': 'schema',
        'USER': 'user',
        'PASSWORD': 'pass',
        'HOST': 'servername',

        'OPTIONS': {
            'driver': 'SQL Server',
        },
    },

Somewhere in django project workspace:

from django.db import connection
cursor = connection.cursor()
cursor.execute(str.format("SELECT id FROM schema.dbo.mytable WHERE num = {0}", obj.num)

I get:

[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'schema.dbo.mytable'. (208) (SQLExecDirectW)

Can anyone help me to detect what's the difference between both? Django is running in the same machine where I run the script, so I believe it isn't a permissions problem...

I would like to use the django connections instead of define a standard cursor, because I prefer to have all the database settings within the django settings, not spread out around the code.


Django's execute format is slightly different. Try this?

cursor.execute("SELECT id FROM schema.dbo.mytable WHERE num = %s", [obj.num])

This will also eliminate a possible SQL Injection attack vector. You probably also want to change your pyodbc query to use bound parameters:

cursor.execute("SELECT id FROM schema.dbo.mytable WHERE num = ?", foo.num)

Good luck!


Finally my problem was that I wanted to open a cursor from a secondary db, not the default one, so the mistake was here:

from django.db import connection
cursor = connection.cursor()

It should be:

from django.db import connections  # instead of connection
cursor = connections['second_db'].cursor()  # using the proper db