好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python调用MySQLdb插入中文乱码的解决

MySQLdb插入中文乱码

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import MySQLdb
def main():
    fullname = "赵钱孙李"
 
    conn = MySQLdb.connect(host='localhost', user='root',passwd='123', db='account', charset='utf8')  # OK
    #conn = MySQLdb.connect(host='localhost', user='root',passwd='123', db='account')  # Error!!!
    cursor = conn.cursor()
    cursor.execute("insert into account (username,password) values ('%s','%s')" % (fullname, "111"))
    conn.commit()
    cursor.close()
    conn.close()
 
if __name__ == "__main__":
    main()

如果从终端查询到数据库中的中文是乱码,那么在连接时给出charset参数即可(当然数据库和表必须全部都是utf-8的)。

否则默认插入的字符应该是latin-1的(用fullname.decode('utf8')时报该错误)。

然后将从数据库中读取的中文输出到网页,如果没有任何内容显示,加入以下代码可解决:

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

Python内部处理编码默认是ascii的:

print sys.getdefaultencoding()

MySQLdb使用utf-8 编码插入中文数据

这几天忙着帮人做一个从网页抓取股票信息并把相应信息存入MySQL中的程序。

使用环境 Python 2.5 for Windows MySQLdb 1.2.2 for Python 2.5 MySQL 4.1.22

在写程序中遇到了些怪的故障。

第一个问题:插入中文失败

这个是由于字符编码问题引起的。MySQL安装时我已经设置为utf8编码,表也是使用utf8编码建立。程序中只要在开头写好#-*- coding: utf-8 -*-,并在设定连接字符串时候写清使用utf8就可以了conn=MySQLdb.connect(host="127.0.0.1",user="webdb",passwd="web123",db="web",charset="utf8")。

设置之后从MySQL中取出的以utf8编码保存的中文也不会发生乱码。 

对中文字符串,如:a = "浦发银行",在进行插入操作前做一下编码转换a = a.decode("gbk").encode("utf-8")。然后进行插入操作就没有任何问题了。

第二个问题:能插入之后无法在MySQL中保存刚才插入的数据

经过检查数据可以被正确的插入,但是连接断开之后不保存在表中。经过检查发现原来是漏了conn.commit()。需要在语句执行之后提交操作。

源代码如下:

?# -*- coding: utf-8 -*-
?import ?sys,MySQLdb
conn = MySQLdb.connect(host = " 127.0.0.1 " ,user = " webdb " ,passwd = " web123 " ,db = " web " ,charset = " utf8 " ) ? ? # 需要设定一下charset为utf-8
?cursor = conn.cursor() ? ? # 生成连接的指针对象
?# 进行字符串编码转换并进行插入
?a ?= ? " 浦发银行 "
a ?= ?a.decode( " gbk " ).encode( " utf-8 " ) ? ? # 编码转换为utf-8
?sql = " insert into stocklist (stockno,stockname) values (%s,%s) " ? ? ?# 生成sql语句
?param = ( ' 600000 ' ,a) ? ? # 生成sql语句的参数
?n ?= ?cursor.execute(sql,param) ? ? # 执行sql语句
# 以上操作等价于n = cursor.execute("insert into stocklist (stockno,stockname) values ('430004','"+ "浦发银行".decode("gbk").encode("utf-8") + "')")
?print ?n
conn.commit() ?# 提交操作结果
?# 进行查询操作检查刚刚执行的插入操作结果
?n ?= ?cursor.execute( " select * from stocklist " )
?for ?row ?in ?cursor.fetchall():
? ? ?print ?row[0] ?+ ?row[ 1 ]
cursor.close() ? ? # 关闭指针
?conn.close() ? ? # 关闭连接

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

查看更多关于Python调用MySQLdb插入中文乱码的解决的详细内容...

  阅读:40次