关于 python MySQLdb 插入 utf-8 字符报编码错误的问题


用 python 第三方 mysql 包在执行一些包含UTF8字符的SQL语句时,往往会见到这样的错误:
‘ascii’ codec can’t encode character ……’
或者
‘latin-1′ codec can’t encode character ……’

其实,我们只需要注意在插入前encode一下即可:

python语句:

01
#coding=utf-8
02
import MySQLdb
03
cc = '我们'
04
conn = MySQLdb.connect(
05
        host="localhost",
06
        user="root",
07
        passwd="root",
08
        port=3306,
09
        db="test1",
10
        init_command="set names utf8"
11
        )
12
 
13
cursor = conn.cursor()
14
cursor.execute("insert into a values('%s')" %(cc.encode('utf-8')))
15
conn.commit()
数据库建表语句:

1
CREATE TABLE `a` (
2
  `name` char(100) DEFAULT NULL
3
) ENGINE=InnoDB DEFAULT CHARSET=utf8
结果(windows下):


01
mysql> set names gbk;
02
Query OK, 0 rows affected (0.00 sec)
03
 
04
mysql> select * from a;
05
+------+
06
| name |
07
+------+
08
| 1    |
09
| 我们 |
10
+------+
11
2 rows in set (0.00 sec)
12
 
13
mysql>

豆瓣是这样解释这个问题的: www.2cto.com

conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db, init_command="set names utf8")

然后用conn就是了,再也不用考虑encoding的事情。

还有一个好处是,如果中间timeout, MySQLdb自动重连时,可以保证新的链接仍然是utf-8。

其实也可以每次手动:cursor.execute("set names utf-8")


作者:xrzs

相关内容

    暂无相关文章

评论关闭