2016-07-31 48 views
0

我想從tweepy StreamListener中檢索文本,經度和緯度,然後將數據存儲在我的SQL數據庫中。我能夠保存好座標,但由於某種原因,unicode無法正常工作。 對於SQL我:從Python腳本插入到MySQL數據庫unicode

mysql> CREATE TABLE tweets (tweet nvarchar(140), lat float(10,6) not null, lng float(10,6) not null) engine=myisam; 

對於我的Python腳本我有(不包括在main()):

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 

請注意,我是初學者所以任何建議表示讚賞。

+0

嘗試在MySQL shell中運行'SET NAMES UTF8;'。 –

+0

ALTER TABLE tweets CONVERT TO CHARACTER SET utf8mb4 – MONTYHS

+0

正如@MONTYHS所說,只需改變表格即可接受unicode。它的數據和你的數據庫,所以只要改變數據庫接受unicode是我認爲最簡單和最正確的解決方案。這個稱爲「字符串編碼」的主題對於開發人員來說可能是壓倒性的。不要在初學者級別掛上這些。請注意,您可以使用MySQL Workbench作爲圖形前端來處理管理和表變更。它可以非常方便。 – Dan

回答

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])) 
相關問題