【问题标题】:Insert latitude and longitude from Python mysql.connector into MySQL using Tweepy使用 Tweepy 将 Python mysql.connector 中的纬度和经度插入 MySQL
【发布时间】:2016-08-21 20:06:47
【问题描述】:

我正在尝试使用 Twitter 流 API 将地理编码推文中的一些推文对象放入 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 行,一切都会打印到控制台。

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

【问题讨论】:

    标签: python mysql twitter geolocation tweepy


    【解决方案1】:

    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))
    

    【讨论】:

    • 谢谢,就是这样!
    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 2015-05-09
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多