- 论坛徽章:
- 0
|
有一个表字段类型是varbinary类型的,如果这个字段里没有中文,那用MySQLdb可以正常读写,如果这个字段里有中文,就提示:
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data
但是如果这个字段类型是varchar的,不管是中文和英文都可以正常读写,请问这个问题怎样解决啊?
代码如下:
# !/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import string
import MySQLdb
reload(sys)
sys.setdefaultencoding("utf-8")
conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "", db = "test", charset = "utf8")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
sql = "SELECT * FROM tb_user where user_name = 'hhqq888'"
result = cursor.execute(sql)
row = cursor.fetchone()
print row["user_name"]
cursor.close()
conn.close()
表结构:
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| pk | bigint(12) | | PRI | 0 | |
| user_name | varchar(40) | YES | MUL | NULL | |
| user_pwd | varbinary(20) | | | | |
| role_code | int(3) | | MUL | 0 | |
| pwd_question | varchar(50) | YES | | NULL | |
| pwd_answer | varbinary(50) | YES | | NULL | |
| memo | varchar(200) | YES | | NULL | |
| status | int(1) | YES | | NULL | |
| type | int(2) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+ |
|