Python, MySQL _mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax

五迷三道 提交于 2020-01-24 21:41:08

问题


Im currently sending a twitter stream to a local MySQL db and I have run into an issue. Whenever a user creates a tweet with " located within it, I will get a syntax error because it messes with the Insert statement.

Im curious of the best way to fix this so a persons tweet will not effect the insert statement.

example variables:

tweetId = 98757629
userId = 07gos870sg
text = "this is "what " is messing up my sql"
day = 04
month = 'dec'
year = 2016
hour = 23
minute = 45
placeId = 'kj4h5b899'


c.execute('INSERT INTO tweet VALUES("%s", "%s", "%s", "%s", "%s", 
           "%s", "%s", "%s", "%s")' % \
           (tweetId, userId, text, day, month, year, hour, minute, placeId))

Iv thought of just taking any of the characters (" ` ') that would mess with he insert statement out before they are sent to the code, however; I dont want to edit any user submitted data.


回答1:


You should bind the variables instead of formatting the sql string.

sql = "INSERT INTO tweet VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
values = (tweetId, userId, text, day, month, year, hour, minute, placeId)
cursor.execute(sql, values)


来源:https://stackoverflow.com/questions/41028774/python-mysql-mysql-exceptions-programmingerror-1064-you-have-an-error-in-y

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!