2008-09-10

Python连接MySQL - [Python]

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://mobile2008.blogbus.com/logs/28725962.html

安装好之后,模块名字叫做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

Python连接MySQL  [Python]#encoding=utf-8
Python连接MySQL  [Python]
importsys
Python连接MySQL  [Python]
importMySQLdb
Python连接MySQL  [Python]
Python连接MySQL  [Python]reload(sys)
Python连接MySQL  [Python]sys.setdefaultencoding(
'utf-8')
Python连接MySQL  [Python]
Python连接MySQL  [Python]db
=MySQLdb.connect(user='root',charset='utf8')
Python连接MySQL  [Python]cur
=db.cursor()
Python连接MySQL  [Python]cur.execute(
'use mydb')
Python连接MySQL  [Python]cur.execute(
'select*from mytb limit100')
Python连接MySQL  [Python]
Python连接MySQL  [Python]f
=file("/home/user/work/tem.txt",'w')
Python连接MySQL  [Python]
Python连接MySQL  [Python]
foriincur.fetchall():
Python连接MySQL  [Python]f.write(str(i))
Python连接MySQL  [Python]f.write(
"")
Python连接MySQL  [Python]
Python连接MySQL  [Python]f.close()
Python连接MySQL  [Python]cur.close()

上面是linux上的脚本,windows下运行正常!

注:MySQL的配置文件设置也必须配置成utf8

设置MySQL的my.cnf文件,在[client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。