zoukankan      html  css  js  c++  java
  • 解决Python 插查 MySQL 时中文乱码问题

    首先找到这里的解决方法,

    count = cursor.fetchall()

    for i in count:

      idc_a = i[0]

      if isinstance(idc_a, unicode):

                idc_a = idc_a.encode('utf-8')

      print idc_a

    但只能解决查询显示乱码问题

    后来继续查资料,找到了这里

    解决方法很简单拿,和数据库建立连接后,执行:

    db.set_character_set('utf8')
    dbc.execute('SET NAMES utf8;')
    dbc.execute('SET CHARACTER SET utf8;')
    dbc.execute('SET character_set_connection=utf8;')

    "db" is the result of MySQLdb.connect, and "dbc" is the result of db.cursor().

    这样基本解决了。在查看评论时,还看到了一种解决方法:

    就是在连接数据库时,指定连接字符集

    A lot of useless methods, mate. It is enough to connect with charset="utf8" param.
    db = MySQLdb.connect(host="localhost", user = "root", passwd = "", db = "testdb", use_unicode=True, charset="utf8")

    当然以上解决方案前提是,数据库在设计时为utf8,表的字符集也要创建为utf8:

    修改表字符集:
    ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

    关于修改MySQL默认字符集,参见这边文章:
    ————>

  • 相关阅读:
    为什么和什么是 DevOps?
    使用jmeter 上传文件
    jmeter 获取执行脚本的路径
    随笔(九)
    随笔(八)
    随笔(七)
    随笔(六)
    随笔(五)
    随笔(四)
    随笔(三)
  • 原文地址:https://www.cnblogs.com/johnchain/p/3416922.html
Copyright © 2011-2022 走看看