开发者

Spaces, Apostrophe, and Ampersand in MySQL Enum Values

I am creating a MySQL Table, and one of column's type is ENUM.

I have several different ENUM values. Some of them are two or more words, e.g. Hugo Boss.

Other ENUM values have an apo开发者_如何学编程strophe in them, e.g. Men's, or other characters, e.g. &.

My question is two part:

  1. It is ok to have one or more spaces in an ENUM value (two words, or more)?
  2. Are apostrophes, ampersands, and other such characters, allowed in ENUM values? And if they are, how would I go about placing them?


Seems so:

MySQL [files]> create temporary table t(foo ENUM('123', '1&2', '3\'4'));
Query OK, 0 rows affected (0.17 sec)

MySQL [files]> show create table t\G
*************************** 1. row ***************************
       Table: t
Create Table: CREATE TEMPORARY TABLE `t` (
  `foo` enum('123','1&2','3''4') COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.09 sec)

MySQL [files]> insert into t values (0), (1), (2), (3);
Query OK, 4 rows affected, 1 warning (0.12 sec)
Records: 4  Duplicates: 0  Warnings: 1

MySQL [files]> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'foo' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.11 sec)

MySQL [files]> select * from t;
+------+
| foo  |
+------+
|      |
| 123  |
| 1&2  |
| 3'4  |
+------+
4 rows in set (0.09 sec)

MySQL [files]>

Note: The warning means that I have used a value which was not allowed - I tried to insert 3, which is not defined as value for the ENUM.

So it works perfectly - as with any other strings in MySQL. You only have to take care that you treat them correctly - either as hex values, or use mysql_real_escape_string() or prepared statements. This provides for correct communication of "critical" values such as \\, ', " etc.

For example, if I have a string which contains "3'4", and I want to define it as a part of an enum, I create the query by putting one of 0x332734 or '3\'4' to the appropriate place. '3\'4' is obtained as a result of mysql_real_escape_string("3'4") in the used programming language.

NUL characters are not allowed as ENUM components as they would be in data strings - the used string is terminated before, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜