mk8efz
mk8efz

Reputation: 1424

Error with Python Cursor

I write a script that inserts in DB directly with the python cursor object

 cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" % (height, manufacturerid, weight)) 

Sometimes I don't have a number for "weight" and it throws an error:

Incorrect syntax near ','. (102) (SQLExecDirectW)")

How you handle errors like this?

Upvotes: 0

Views: 278

Answers (3)

sberry
sberry

Reputation: 132138

You should NOT be using string formatting for sql queries. Let that get handled at a layer more apt:

Instead of:

cursor.execute("INSERT INTO info ([height], [weight], [type]) VALUES (%s,%s,%s)" %(height, manufacturerid, weight))

Use

cursor.execute("INSERT INTO info ([height], [weight], [type]) VALUES (%s,%s,%s)", (height, manufacturerid, weight))

will likely fix your problem, and not be subject to sql injection or problems like the one you are having.

Since this seems to be Oracle, and I have not used it with Python, refer to the docs, but PEP 249 states that the placeholders for parameterized queries are: https://www.python.org/dev/peps/pep-0249/#paramstyle

Upvotes: 0

Carlos Parra
Carlos Parra

Reputation: 1067

According with the docs, you should never do the query like this (the way you have):

cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" % (height, manufacturerid, weight))

You should do it as follows:

cursor.execute("INSERT INTO info ([height], [weight],[type]) VALUES (%s,%s,%s)" , (height, manufacturerid, weight))

Check this for more help.

Upvotes: 1

Sven Hakvoort
Sven Hakvoort

Reputation: 3621

With try, except see the python docs: https://docs.python.org/2/tutorial/errors.html

Upvotes: 0

Related Questions