简体   繁体   中英

python MySQLdb prepared select statement

In python with MySQLdb I am trying to execute the following:

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d)" % (curRow, curCol) 

r and c are integer fields in table adjacency and also form a composite primary key. curRow and curCol are integer variables in my python program. MySQL is complaining:

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%d and c = %d' at line 1") 

Ultimately, I want to check if there already exists a row in adjacency with r=curCow and c=curCol . If so, then update a field in the table. Otherwise insert a row into the table.

  1. What is wrong with my prepared statement?

All help is greatly appreciated!

Looks like you just have a bracket in the wrong place.

Change...

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d)" % (curRow, curCol)

...to...

cur.execute("select COUNT(*) from adjacency where r = %d and c = %d" % (curRow, curCol))

...although it's safer to use...

cur.execute("select COUNT(*) from adjacency where r = %s and c = %s", (curRow, curCol))

...which will protect you from potential SQL injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM