zhaohaolin 发表于 2013-1-31 02:27:22

Python操作MySQL以及中文乱码的问题

http://blog.csdn.net/images/authorship.gif Python操作MySQL以及中文乱码的问题收藏

Python操作MySQL需要安装Python-MySQL
可以从网上搜索一下,和一般的Python包一样安装

安装好之后,模块名字叫做MySQLdb ,在Window和Linux环境下都可以使用,试验了一下挺好用,
不过又发现了烦人的乱麻问题,最后用了几个办法,解决了!

我用了下面几个措施,保证MySQL的输出没有乱麻:
    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
    2 MySQL数据库charset=utf-8
    3 Python连接MySQL是加上参数 charset=utf8
    4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

mysql_test.py
   <div style="">http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif#encoding=utf-8
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifimport sys
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifimport MySQLdb
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifreload(sys)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifsys.setdefaultencoding('utf-8')
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifdb=MySQLdb.connect(user='root',charset='utf8')
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifcur=db.cursor()
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifcur.execute('use mydb')
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifcur.execute('select * from mytb limit 100')
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.giff=file("/home/user/work/tem.txt",'w')
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.giffor i in cur.fetchall():
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif    f.write(str(i))
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif    f.write(" ")
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.giff.close()
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifcur.close()
页: [1]
查看完整版本: Python操作MySQL以及中文乱码的问题