python - Unicode解码错误: 'ascii' codec can't decode byte 0xe2 in position 139: ordinal not in range(128)

标签 python mysql python-2.7 twitter

我正在编写一个代码,它根据搜索词从 Twitter 获取实时推文并将其保存到 Mysql 数据库。但是,当我在插入数据库的同时运行代码时,会引发错误:

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

这里的 body 是 tweet 中的文本,status 是它是否被处理。

最佳答案

不要将你的推文编码为 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))

是的,上面的代码和你的有区别; tweetiduseridtext 值都作为一个单独的参数(一个元组)传递给 cursor.execute() 方法。

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

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

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

或者更好的是,将数据库配置为使用 UTF8MB4 字符集(MySQL 使用的 UTF-8 版本无法处理表情符号或 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')

关于python - Unicode解码错误: 'ascii' codec can't decode byte 0xe2 in position 139: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32669739/

相关文章:

python - 打印具有不同条目数的表

python - 如何在 Pandas 中找到哪个值计数 n 次?

php - 为什么输入的关键字没有存储在数据库中?

php - MySQL 授予所有权限不允许在 Google CloudSQL 上创建用户

python - 如何在 python 中将两个列表组合成列表列表?

python - 有选择地替换 DataFrames 列名称

python - 格式化表中的数组数据

MySQL : How to synchronize databases after having been offline using replication?

python - 如何让 Tornado 在 ssh 连接断开时不停止?

python - 如何在 Robot Framework 中获取当前测试用例状态通过/失败