Django Forms pyodbc Mssql TypeError: not all arguments converted during string formatting

887 Views Asked by At

I'm developing an web app alongside an existing windows app on SQL server 2014.Using the following settings

DATABASES = {
'default': {
    'NAME': ' Name',
    'ENGINE': 'sql_server.pyodbc',
    'SERVER': 'server',
    'USER': 'sa',
    'PASSWORD': 'password',

    'OPTIONS':
     {
     'driver_supports_utf8': True,
      'autocommit': True,
      'unicode_results': True,
      'host_is_server':True,
      'driver': 'SQL Server Native Client 11.0',
      }
    }
    }

I'm Using stored procedures in my django app to use the existing functionalities

class Viewpatform(forms.Form):
Name = forms.CharField(max_length=100)
Phone_Number = forms.IntegerField(label='Phone Number', required=True)
Sex = forms.ChoiceField(widget=forms.Select(choices=sexchoice))
Age = forms.IntegerField(label='Age')
AgeType = forms.ChoiceField(choices=Agetype,  required=True,  label='Type')
Address = forms.CharField(max_length=500, required=False)
Registration_Date = forms.DateField( label='Registration Date')
with connection.cursor() as cursor:
   cursor.execute(''' EXEC dbo.insert_patients @Name = ?, -- varchar(100)
    @Phone_Number = ?, -- int
    @Age = ?, -- int
    @AgeType = ?, -- int
    @Address = ?, -- varchar(200)
    @sex = ? -- varchar(2)
         ''', [ Name, Phone_Number, Sex, Age, AgeType, Address] )

I have been getting the following errors while executing the form

File "c:\python35\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "c:\python35\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "c:\python35\lib\site-packages\sql_server\pyodbc\base.py", line 535, in execute sql = self.format_sql(sql, params) File "c:\python35\lib\site-packages\sql_server\pyodbc\base.py", line 503, in format_sql sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting

Django ver 1.10 Windows 7 64 bit Django-Pyodbc-azure : Version: 1.10.4.0 Python 3.5

1

There are 1 best solutions below

0
FlipperPA On BEST ANSWER

Your arguments appear to be out of order. You must pass the arguments in the list of parameters in the same order as the question mark place holders:

cursor.execute(
    '''
        EXEC dbo.insert_patients
            @Name = ?, -- varchar(100)
            @Phone_Number = ?, -- int
            @Age = ?, -- int
            @AgeType = ?, -- int
            @Address = ?, -- varchar(200)
            @sex = ? -- varchar(2)
    ''',
    [Name, Phone_Number, Age, AgeType, Address, Sex]
)

You're getting the error because you're passing integers as strings and strings as integers, AFAIK. Good luck!