How to Insert in SQL using django app but getting COUNT field incorrect or syntax error

Question:

I want to insert data from django to SQL but getting error :

(‘07002’, ‘[07002] [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error (0) (SQLExecDirectW)’)

My code is below:

for connection:

def connsql():
    server = ''
    database = ''
    username = ''
    password = ''
    conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
    return conn

for storing data in db:
    connectionString=self.connsql()
    saveDetails=ModelClass()
    todayDate=date.today()
    saveDetails.Date=todayDate.strftime('%m/%d/%Y')
    saveDetails.Questions=question
    saveDetails.Result=str(result)
    cursor=connectionString.cursor()
    cursor.execute("insert into [dbo].[testtable](Date,Questions,Result) values ("+saveDetails.Date+"','"+saveDetails.Questions+"','"+saveDetails.Result+");")
    cursor.commit()

As I’m new to this any help will be thankfull.

Asked By: Shubh kumar

||

Answers:

I think you have an error in your syntax

Try

cursor.execute("insert into [dbo].[testtable] (Date,Questions,Result) values ('"+saveDetails.Date+"','"+saveDetails.Questions+"','"+saveDetails.Result+"');")

You should consider writing your Queries to avoid injectionattacks and ensure proper handling of special characters.

cursor.execute("insert into [dbo].[testtable] (Date,Questions,Result) values (?, ?, ?)", saveDetails.Date, saveDetails.Questions, saveDetails.Result)
Answered By: kincaid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.