2015-09-19 273 views
1

我正在研究一个代码,它根据搜索词从Twitter获取实时tweets并将其保存到Mysql数据库。但是,当我运行的代码,而插入到数据库它提出了一个错误:UnicodeDecodeError:'ascii'编解码器无法解码位置139中的字节0xe2:序号不在范围内(128)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 139: ordinal not in range(128) 

我不明白有什么问题就在这里是代码插入到数据库

tweet = json.loads(data); 
    #print json.dumps(tweet, indent=4, sort_keys=True) 
    #print tweet['text'] 
    tweetid = tweet['id_str'] 
    userid = tweet['user']['id_str'] 
    text = tweet['text'].encode('utf-8') 
    cur.execute("""INSERT INTO twitterfeeeds(tweet_id, user_id,body,status) VALUES (%s,%s,%s,'0')"""%(tweetid,userid,text)) 
    db.commit() 

这里的身体是在鸣叫文本状态是它是否被处理。

回答

3

不要将您的推文编码为UTF-8,也不要使用字符串格式创建查询。

使用SQL参数代替:

tweetid = tweet['id_str'] 
userid = tweet['user']['id_str'] 
text = tweet['text'] 
cur.execute(
    """INSERT INTO twitterfeeeds(tweet_id, user_id,body,status) VALUES (%s, %s, %s, '0')""", 
    (tweetid, userid, text)) 

是,有上述代码和你之间的差值; tweetid,useridtext值都作为一个单独的参数(元组)传递给cursor.execute()方法。

游标有责任处理正确的转义数据以插入数据库。这样您可以避免SQL注入攻击(与;DROP TABLE twitterfeeeds的推文会立即破坏您的数据库),并启用查询计划优化。

这一切都需要您配置数据库连接以支持Unicode数据;字符集设置为UTF-8的连接:

conn = MySQLdb.connect(host="localhost", user='root', password='', 
         db='', charset='utf8') 

或者更好的是,配置数据库使用UTF8MB4字符集(的UTF-8版本的MySQL应用无法处理的表情符号或其他代码点超出U + FFFF):

# Note, no characterset specified 
con = MySQLdb.connect(host="localhost", user='root', password='', db='') 
cursor = con.cursor() 
cursor.execute('SET NAMES utf8mb4') 
cursor.execute('SET CHARACTER SET utf8mb4') 
cursor.execute('SET character_set_connection=utf8mb4') 
+0

鸣叫时不进行编码,它提出了另一个错误 UnicodeEncodeError:“拉丁-1 '编解码器不能在位置234对字符u'\ u2026'进行编码:序号不在范围内(256) – Harwee

+0

@Harwee:不作为查询参数传递时。 –

+0

@Harwee:您确实需要将数据库配置为接受UTF-8 Unicode文本,目前您的数据库只能处理Latin-1。 –

1

使用可以使用MySQLdb.escape_string来转义unicode字符。

>> MySQLdb.escape_string("'") 
"\\'" 

此外,我认为你必须与 'use_unicode' 打开 'mysql.connector':真正的配置:

config = { 
'user': ..., 
'password': ..., 
'host': '127.0.0.1', 
'use_unicode':True, 
'charset':'utf8', 
} 
db = mysql.connector.connect(**config) 
相关问题