简体   繁体   中英

Python SQL syntax error

Im trying to run a python script on my raspberry pi, in order to store the data that I receive from the gps receiver into a sql table. While Im executing this script I'm getting an error on this part of the code:

sql = "INSERT INTO gps (n_lat, w_long, date_time) VALUES (%s, %s, %s)" % (north, west, t,)
print sql
cur.execute(sql)
print "Rows inserted: %s" % cur.rowcount
con.commit()
time.sleep(0.5)

Error:

Traceback (most recent call last):
File "gps.py", line 48, in <module>
  cur.execute(sql)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
  self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue
_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 ':01:16)' at line 1")

I don't really understand where is the problem, Have you got any ideas why whiz error occurs ?

您在引号内设置了值的SQL语句中的错误:

VALUES ('%s', '%s', '%s')

You did not escape your input values. For numbers this is optional, but datetime might not be a number.

However, you should always escape input values for your database. The keyword here is prepared statements . Instead of parsing your input arguments into the string with pythons % operater, you should use the argument list of cursor.execute .

sql = "INSERT INTO gps (n_lat, w_long, date_time) VALUES (%s, %s, %s)"
print sql
cur.execute(sql, (north, west, t,))
print "Rows inserted: %s" % cur.rowcount
con.commit()
time.sleep(0.5)

Now the function execute will make sure, that all special characters are escaped. Eg one of your input values might contain a single quote or similar. Using python's string parsing, this would result in something like:

"INSERT INTO gps (n_lat, w_long, date_time) VALUES ('123', '123', '1234'321')"

In best case this would result in a database error, in worst case somebody could manipulate your database with his own SQL statements (so called 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