mysql> use varchar_vs_char;
Database changed
mysql> desc user;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | 0 | |
| username | varchar(10) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
可以插入的数据:
mysql> use varchar_vs_char;
Database changed
mysql> select * from user;
+----+----------------------+
| id | username |
+----+----------------------+
| 1 | adminadmin |
| 2 | 我是中国人我是中国人 |
+----+----------------------+
2 rows in set (0.01 sec)
也就是说对于unicode来说一个英文字符和一个中文字符是一样大小的,而且varchar(10)中的10就是表示10个unicode码!
因为是处理中文的,所以把D:\Program Files\MySQL\MySQL Server 5.1\my.ini编码设置成如下gbk:
[client]
port=3306
[mysql]
default-character-set=gbk
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]
# The TCP/IP Port the MySQL Server will listen on
port=3306
#Path to installation directory. All paths are usually resolved relative to this.
basedir="D:/Program Files/MySQL/MySQL Server 5.1/"
#Path to the database root
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/"
# The default character set that will be used when a new schema or table is
# created and no character set is defined
default-character-set=gbk
# The default storage engine that will be used when create new tables when
default-storage-engine=INNODB
附注:
更新的数据中有中文,出现如下错误:
OperationalError at /admin/blog/post/add/
(1366, "Incorrect string value: '\\xE6\\xB7\\xB1\\xE5\\x85\\xA5...' for column 'title' at row 1")
Request Method: POST
Request URL: http://localhost:8000/admin/blog/post/add/
Exception Type: OperationalError
Exception Value:
(1366, "Incorrect string value: '\\xE6\\xB7\\xB1\\xE5\\x85\\xA5...' for column 'title' at row 1")
Exception Location: C:\Python25\Lib\site-packages\MySQLdb\connections.py in defaulterrorhandler, line 35
类似这样的错误,应该是数据库表的charset和collation问题。尝试把所有表的charset改为utf-8, collation改为utf8-unicode-ci。如果还是不能解决,最好是重建数据库,然后修改数据库的属性,选择charset为utf-8,collation为utf8-unicode-ci。命令行:create database cc default charset utf8 collate utf8_unicode_ci;
PS:我就是要重建数据库才解决。