MySQL中varchar和char定義長度是字元,與Oracle nvarchar2類似

denglt發表於2014-02-18
今天測試了下MySQL的字元型別varchar,發現與Oracle nvarchar2型別相似,定義的是字元長度,而非位元組長度。

mysql> select @@version;
+------------------+
| @@version        |
+------------------+
| 5.6.14-ndb-7.3.3 |
+------------------+
1 row in set (0.00 sec)

mysql> desc test1;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name  | varchar(10) | YES  |     | NULL    |       |
| name2 | char(10)    | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

 

mysql> select length(name),name,length(name2),name2 from test1;
+--------------+--------------------------------+---------------+--------------------------------+
| length(name) | name                           | length(name2) | name2                          |
+--------------+--------------------------------+---------------+--------------------------------+
|           18 | 鄧小平好人人人人人             |            18 | 鄧小平好人人人人人             |
|           10 | 鄧小平好人                     |            10 | 鄧小平好人                     |
|           10 | 0123456789                     |            10 | 0123456789                     |
|           20 | 鄧小平好人人人人人人           |            20 | 鄧小平好人人人人人人           |
|            6 | 鄧小平                         |             6 | 鄧小平                         |
|           12 | 鄧小平好人人                   |            12 | 鄧小平好人人                   |
+--------------+--------------------------------+---------------+--------------------------------+
6 rows in set (0.00 sec)



mysql> insert into test1 (name) values('12345678901');
ERROR 1406 (22001): Data too long for column 'name' at row 1
mysql> insert into test1 (name2) values('12345678901');
ERROR 1406 (22001): Data too long for column 'name2' at row 1
 
 
網上的另一篇說明這個的文章:http://cau99.blog.51cto.com/1855224/383023/

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/195110/viewspace-1083351/,如需轉載,請註明出處,否則將追究法律責任。

相關文章