Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mysql中文乱码的问题 #6

Open
mkdir1 opened this issue Jan 7, 2016 · 0 comments
Open

mysql中文乱码的问题 #6

mkdir1 opened this issue Jan 7, 2016 · 0 comments

Comments

@mkdir1
Copy link
Owner

mkdir1 commented Jan 7, 2016

背景

之前处理mysql没有涉及到中文,故对此无所用心.今于此耗时逾一日,算是小有收获

问题

mysql上字段存储中文

解决过程中出现的问题

-1. 在`python源文件头添加

reload(sys)                                                                                                                                                                  
sys.setdefaultencoding('utf8')

或听信网上一种方法:

File "getAnswer.py", line 12, in <module>
    sys.setdefaultencoding('gb2313')
LookupError: unknown encoding: gb2313
  1. 字符encode或decode后存储到mysql中
    结果乱码
  2. 在存储操作前调用一个set字符的操作

以上前徒劳,最后解决方案:

 self.cursor.execute("DROP TABLE IF EXISTS answer")
               create_answer_sql = '''CREATE TABLE answer(
              question_id varchar(30) NOT NULL,                                                                                                                                
               question text(300) NOT NULL,
           answer_id varchar(30) NOT NULL,
               answer text(3000) NOT NULL
   )DEFAULT CHARSET=utf8'''

即在创建数据表时,设置为utf8

原因

因为mysql默认的编码是latin1,所以,当是ascii码时,是没问题的,当字符是utf8时,在mysql中无论如何是无法正确显示成中文的,只能是把table的编码也设置成utf8

还有就是,当python文件首项设置成'utf8'时,得到的就是这个编码,就可以直接存储到mysql中

查询表的charset

show create table answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant