简体   繁体   English

Python SQL语法错误

[英]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. 我试图在树莓派上运行python脚本,以便将我从gps接收器接收的数据存储到sql表中。 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 . 不应使用pythons % operr将输入参数解析为字符串,而应使用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. 现在,函数execute将确保所有特殊字符均已转义。 Eg one of your input values might contain a single quote or similar. 例如,您的一个输入值可能包含单引号或类似的引号。 Using python's string parsing, this would result in something like: 使用python的字符串解析,这将导致类似:

"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 ). 在最好的情况下,这将导致数据库错误,在最坏的情况下,有人可以使用自己的SQL语句(即所谓的SQL注入 )来操纵数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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