从python脚本将unicode插入MySQL数据库

时间:2016-07-31 18:02:37

标签: python mysql tweepy

我试图从tweepy StreamListener中检索文本,经度和纬度,然后将数据存储在我的SQL数据库中。我可以很好地存储坐标,但由于某种原因,unicode无法正常工作。 对于SQL我有:

import mysql.connector
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from authenticator import Authenticator
import json


#connecting to mysql database
conn = mysql.connector.connect(user='root', password='arlenyu123',host='localhost',database='twitter')
mycursor = conn.cursor()


class MyStreamListener(StreamListener):

    def on_status(self, status):
        if status.coordinates is not None:
            #for some reason the status text isn't being fed into the database properly... not sure why.
            mycursor.execute('INSERT INTO tweets (tweet, lat, lng) VALUES ({},{},{})'.
                format(status.text, status.coordinates['coordinates'][0], status.coordinates['coordinates'][1]))
    return True

def on_error(self, status_code):
    if status_code == 403:
        print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached")
        return False

对于我的python脚本,我有(不包括main()):

build-impl.xml:1045: The module has not been deployed.

请注意我是初学者,所以感谢任何建议。

1 个答案:

答案 0 :(得分:0)

您应该从不使用字符串插值来创建SQL命令。使用SQL连接器提供的参数替换。

 mycursor.execute('INSERT INTO tweets (tweet, lat, lng) VALUES (%s,%s,%s)',
                  (status.text, status.coordinates['coordinates'][0], status.coordinates['coordinates'][1]))