user = "'" + "@%s" % data['user']['screen_name'] + "'"
coordinates = "'" + ",".join(str(e)for e in data['coordinates']['coordinates']) + "'"
tweet = "'" + data['text'].encode("ascii", "ignore") + "'"
query = "INSERT INTO tweets (location, tweet, author) values (" + coordinates + "," + tweet + "," + user + ")"
我遇到传票的问题是有撇号(')或随机引号打破了插入查询。任何建议都会受到赞赏,因为我希望减少推文插入的错误。感谢
示例错误消息:
(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 's Stadium https://t.co/uJ2U2tcXlr','@Pucker21')' at line 1")
答案 0 :(得分:0)
这是不应该通过字符串插值手动构造查询的原因之一。
相反,让数据库驱动程序处理它:
query = """
INSERT INTO
tweets
(location, tweet, author)
VALUES
(%s, %s, %s)
"""
cursor.execute(query, (coordinates, tweet, user))
我们在这里创建一个参数化查询,%s
是要填充的数据库驱动程序的占位符。 MySQL驱动程序将处理正确的引用,转义并使查询不受SQL注入。