mysql中的python编码 [英] mysql in python encoding

查看:101
本文介绍了mysql中的python编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章与我在 MySQL中的Python中的问题相同:UnicodeEncodeError:'ascii'这只是为了清除事情。

This post is the same with my question in MySQL in Python: UnicodeEncodeError: 'ascii' this is just to clear things up.

我试图将一个字符串保存到MySQL数据库,但是我收到一个错误:

I am trying to save a string to a MySQL database but I get an error:


文件.smart.py,第51行,
(number,text,'smart','u')

File ".smart.py", line 51, in (number, text, 'smart', 'u')

UnicodeDecodeError:'ascii'编解码器无法解码位置
的字节0xc2 25:序号不在范围(128)

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

,字符串保存在 m ['Text']

and the string is saved at m['Text']


Lala * =#&%@<> _?!:; - '/()¥¡¿

Lala*=#&%@<>_?!:;-'"/()¥¡¿

这是代码片段

risk = m['Text']
msg = risk.encode('utf8')
text = db.escape_string(msg)

sql = "INSERT INTO posts(nmbr, \
       msg, tel, sts) \
       VALUES ('%s', '%s', '%s', '%s')" % \
       (number, text, 'smart', 'u')

如果我尝试注释掉SQL查询并将 打印文本 它将打印出Lala * =#&%@<> _?!:; - '/()¥¡¿

If i try to comment out the SQL query and put print text it would print out Lala*=#&%@<>_?!:;-'"/()¥¡¿

错误只在处理SQL时遇到。

The error is only encountered when the SQL is being processed.

MySQL编码设置为utf8_unicode_ci。 (或者我应该改变这个?)

MySQL encoding is set to utf8_unicode_ci. (or should i change this?)

谢谢。

推荐答案

添加这些参数 MySQLdb.connect(...,use_unicode = 1,charset =utf8)

创建游标

cur = db.cursor()

然后执行如下:

risk = m['Text']
sql = """INSERT INTO posts(nmbr, msg, tel, sts) \
         VALUES (%s, %s, %s, %s)"""
values = (number, risk, 'smart', 'u')
cur.execute(sql,values)  #use comma to separate sql and values, this will ensure values are escaped/sanitized
cur.commit()

现在你不需要这两行:

msg = risk.encode('utf8')
text = db.escape_string(msg)

这篇关于mysql中的python编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆