Python连接MySQL - [Python]

Python连接MySQL - 冷眼看Mobile Web——by damon - 博客大巴

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

# encoding=utf-8
import  sys
import  MySQLdb

reload(sys)
sys.setdefaultencoding(
' utf-8 ' )

db
= MySQLdb.connect(user = ' root ' ,charset = ' utf8 ' )
cur
= db.cursor()
cur.execute(
' use mydb ' )
cur.execute(
' select * from mytb limit 100 ' )

f
= file( " /home/user/work/tem.txt " , ' w ' )

for  i  in  cur.fetchall():
    f.write(str(i))
    f.write(
" " )

f.close()
cur.close()

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

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

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

你可能感兴趣的:(python)