使用Tweepy将Python mysql.connector中的纬度和经度插入MySQL

时间:2016-04-27 13:29:34

标签: python mysql twitter geolocation tweepy

我正在尝试使用Twitter Streaming API将一些来自地理编码推文的Tweet对象放入MySQL数据库中的列中。一切都很顺利,但我不知道怎么不能得到数据库的纬度和坐标。

这是我的代码:

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import mysql.connector
from mysql.connector import errorcode
import json
import datetime

cnx = mysql.connector.connect(user='root', password='',
                              host='localhost',
                              database='twitterdb',
                              charset = 'utf8mb4')
cursor=cnx.cursor()

ckey=""
csecret=""
atoken=""
asecret=""

class listener(StreamListener):

    def on_status(self, status):

        if status.coordinates is not None:
          created_at = status.created_at
          username = status.user.screen_name
          tweet = str(status.text)
          long = str(status.coordinates['coordinates'][0])  
          lat = str(status.coordinates['coordinates'][1])

        else:
            return

        print((str(created_at),ascii(username),ascii(tweet),long,lat))

        cursor.execute("INSERT into tweettablegeo (created_at, username, tweet, long, lat) VALUES (%s,%s,%s,%s,%s)",(created_at, username, tweet, long, lat))

        cnx.commit()
        return

    def on_error(self, status):
        print(status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

twitterStream = Stream(auth, listener())
twitterStream.filter(locations=[-180,-90,180,90], stall_warnings = True)

我收到了错误 "mysql.connector.errors.ProgrammingError: 1064 (42000): 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 'long, lat) VALUES ("

如果我注释掉cursor.executecnx.commit行,那么一切都打印到控制台就好了。

我真的没有任何编码背景,所以感谢您给我的任何见解!

1 个答案:

答案 0 :(得分:2)

long是MySQL中的reserved word。要在查询中将其用作列名,必须引用它:

cursor.execute("INSERT into tweettablegeo (created_at, username, tweet, "
               "`long`, lat) VALUES (%s, %s, %s, %s, %s)", 
               (created_at, username, tweet, long, lat))