varchar(n)
n就是指你希望存放的最大字符数(一个汉字、一个英文字母、一个数字都是一个字符)
The CHAR and VARCHAR types are declared with a length
that indicates the maximum number of characters you want to store.
For example, CHAR(30) can hold up to 30 characters.
n最多可以是多少?
The length can be specified as a value from 0 to 65,535.
The effective maximum length of a VARCHAR is subject to
the maximum row size (65,535 bytes, which is shared
among all columns) and the character set used.
这里的限制是字节的限制,不仅要考虑列字段的长度限制,还要考虑整个行数据的长度限制。在gbk编码下,一个汉字最多占用2个字节;在utf-8编码下,一个汉字最多占用3个字节(有待考证,不确定是3还是4)。
测试表
CREATE TABLE `test` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
mysql> insert into test(name) values('abcdeabcdeabcdeabcde');
Query OK, 1 rows affected (0.04 sec)
mysql> insert into test(name) values('abcdeabcdeabcdeabcdea');
Data too long for column 'name' at row 1
mysql> insert into test(name) values('我是中国人我是中国人我是中国人我是中国人');
Query OK, 1 rows affected (0.08 sec)
mysql> insert into test(name) values('我是中国人我是中国人我是中国人我是中国人我');
Data too long for column 'name' at row 1
mysql> insert into test(name) values('12345678901234567890');
Query OK, 1 rows affected (0.05 sec)
mysql> insert into test(name) values('123456789012345678901');
Data too long for column 'name' at row 1
int(n)
int is always 4 bytes wide. The n is the "display width"
显示宽度并不限制可以在列内保存的值的范围,也不限制超过列的指定宽度的值的显示。
在创建表的时候,如果确定不会有负值,最好指定为ungsighed,即无符号:0~4294967295;