Using Character Sets and Unicode
All strings sent from the JDBC driver to the server are converted automatically from native Java Unicode form to the client character encoding, including all queries sent usingStatement.execute(),Statement.executeUpdate(),Statement.executeQuery()as
well as allPreparedStatementandCallableStatementparameters
with the exclusion of parameters set usingsetBytes(),setBinaryStream(),setAsciiStream(),setUnicodeStream()andsetBlob().
Number of Encodings Per Connection
In MySQL Server 4.1 and higher, Connector/J supports a single character encoding between client and server, and any number of character encodings for data returned by the server to the client inResultSets.
Prior to MySQL Server 4.1, Connector/J supported a single character encoding per connection, which could either be automatically detected from the server configuration, or could be configured by the user through theuseUnicodeandcharacterEncodingproperties.
Setting the Character Encoding
The character encoding between client and server is automatically detected upon connection. You specify the encoding on the server using thecharacter_set_serverfor
server versions 4.1.0 and newer, andcharacter_setsystem
variable for server versions older than 4.1.0. The driver automatically uses the encoding specified by the server. For more information, seeSection10.1.3.1,
“Server Character Set and Collation”.
For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server withcharacter_set_server=utf8mb4,
and leavecharacterEncodingout of the
Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.
To override the automatically detected encoding on the client side, use thecharacterEncodingproperty
in the URL used to connect to the server.
To allow multiple character sets to be sent from the client, use the UTF-8 encoding, either by configuringutf8as
the default server character set, or by configuring the JDBC driver to use UTF-8 through thecharacterEncodingproperty.
When specifying character encodings on the client side, use Java-style names. The following table lists MySQL character set names and the corresponding Java-style names:
Table22.26.MySQL to Java Encoding Name Translations
|
MySQL Character Set Name |
Java-Style Character Encoding Name |
|---|
ascii
|
US-ASCII
|
big5
|
Big5
|
gbk
|
GBK
|
sjis
|
SJIS (or Cp932 or MS932 for MySQL Server < 4.1.11)
|
cp932
|
Cp932 or MS932 (MySQL Server > 4.1.11)
|
gb2312
|
EUC_CN
|
ujis
|
EUC_JP
|
euckr
|
EUC_KR
|
latin1
|
Cp1252
|
latin2
|
ISO8859_2
|
greek
|
ISO8859_7
|
hebrew
|
ISO8859_8
|
cp866
|
Cp866
|
tis620
|
TIS620
|
cp1250
|
Cp1250
|
cp1251
|
Cp1251
|
cp1257
|
Cp1257
|
macroman
|
MacRoman
|
macce
|
MacCentralEurope
|
utf8
|
UTF-8
|
ucs2
|
UnicodeBig
|
MySQL官方:MySQL连接字符集设置
Several character set and collation system variables relate to a client's interaction with the server. Some of these have been mentioned in earlier sections:
Additional character set and collation system variables are involved in handling traffic for the connection between a client and the server. Every client has connection-related character set and collation system variables.
A“connection”is
what you make when you connect to the server. The client sends SQL statements, such as queries, over the connection to the server. The server sends responses, such as result sets or error messages, over the connection back to the client. This leads to several
questions about character set and collation handling for client connections, each of which can be answered in terms of system variables:
-
What character set is the statement in when it leaves the client?
The server takes thecharacter_set_clientsystem
variable to be the character set in which statements are sent by the client.
-
What character set should the server translate a statement to after receiving it?
For this, the server uses thecharacter_set_connectionandcollation_connectionsystem
variables. It converts statements sent by the client fromcharacter_set_clienttocharacter_set_connection(except
for string literals that have an introducer such as_latin1or_utf8).collation_connectionis
important for comparisons of literal strings. For comparisons of strings with column values,collation_connectiondoes
not matter because columns have their own collation, which has a higher collation precedence.
-
What character set should the server translate to before shipping result sets or error messages back to the client?
Thecharacter_set_resultssystem
variable indicates the character set in which the server returns query results to the client. This includes result data such as column values, and result metadata such as column names and error messages.
Clients can fine-tune the settings for these variables, or depend on the defaults (in which case, you can skip the rest of this section). If you do not use the defaults, you must change the character settingsfor
each connection to the server.
Two statements affect the connection-related character set variables as a group:
-
SET NAMES 'charset_name'
[COLLATE 'collation_name']
SET NAMESindicates what character set
the client will use to send SQL statements to the server. Thus,SET
NAMES 'cp1251'tells the server,“future
incoming messages from this client are in character setcp1251.”It
also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use aSELECTstatement.)
ASET NAMES 'charset_name'statement
is equivalent to these three statements:
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;
Settingcharacter_set_connectiontocharset_namealso
implicitly setscollation_connectionto
the default collation forcharset_name.
It is unnecessary to set that collation explicitly. To specify a particular collation, use the optionalCOLLATEclause:
SET NAMES 'charset_name' COLLATE 'collation_name'
-
SET CHARACTER SETcharset_name
SET CHARACTER SETis similar toSET
NAMESbut setscharacter_set_connectionandcollation_connectiontocharacter_set_databaseandcollation_database.
ASET CHARACTER SETcharset_namestatement
is equivalent to these three statements:
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET collation_connection = @@collation_database;
Settingcollation_connectionalso
implicitly setscharacter_set_connectionto
the character set associated with the collation (equivalent to executingSET
character_set_connection = @@character_set_database). It is unnecessary to setcharacter_set_connectionexplicitly.
Note
ucs2,utf16,
andutf32cannot be used as a client character
set, which means that they do not work forSET
NAMESorSET CHARACTER SET.
The MySQL client programsmysql,mysqladmin,mysqlcheck,mysqlimport,
andmysqlshowdetermine the default character
set to use as follows:
-
In the absence of other information, the programs use the compiled-in default character set, usuallylatin1.
-
The programs can autodetect which character set to use based on the operating system setting, such as the value of theLANGorLC_ALLlocale
environment variable on Unix systems or the code page setting on Windows systems. For systems on which the locale is available from the OS, the client uses it to set the default character set rather than using the compiled-in default. For example, settingLANGtoru_RU.KOI8-Rcauses
thekoi8rcharacter set to be used. Thus,
users can configure the locale in their environment for use by MySQL clients.
The OS character set is mapped to the closest MySQL character set if there is no exact match. If the client does not support the matching character set, it uses the compiled-in default. For example,ucs2is
not supported as a connection character set.
C applications can use character set autodetection based on the OS setting by invokingmysql_options()as
follows before connecting to the server:
mysql_options(mysql,
MYSQL_SET_CHARSET_NAME,
MYSQL_AUTODETECT_CHARSET_NAME);
-
The programs support a--default-character-setoption,
which enables users to specify the character set explicitly to override whatever default the client otherwise determines.
Note
Before MySQL 5.5, in the absence of other information, the MySQL client programs used the compiled-in default character set, usuallylatin1.
An implication of this difference is that if your environment is configured to use a non-latin1locale,
MySQL client programs will use a different connection character set than previously, as though you had issued an implicitSET
NAMESstatement. If the previous behavior is required, start the client with the--default-character-set=latin1option.
When a client connects to the server, it sends the name of the character set that it wants to use. The server uses the name to set thecharacter_set_client,character_set_results,
andcharacter_set_connectionsystem
variables. In effect, the server performs aSET
NAMESoperation using the character set name.
With themysqlclient,
to use a character set different from the default, you could explicitly executeSET
NAMESevery time you start up. To accomplish the same result more easily, add the--default-character-setoption
setting to yourmysqlcommand
line or in your option file. For example, the following option file setting changes the three connection-related character set variables set tokoi8reach
time you invokemysql:
[mysql]
default-character-set=koi8r
If you are using themysqlclient
with auto-reconnect enabled (which is not recommended), it is preferable to use thecharsetcommand
rather thanSET NAMES. For example:
mysql> charset utf8
Charset changed
Thecharsetcommand issues aSET
NAMESstatement, and also changes the default character set thatmysqluses
when it reconnects after the connection has dropped.
Example: Suppose thatcolumn1is defined
asCHAR(5) CHARACTER SET latin2. If you
do not saySET NAMESorSET
CHARACTER SET, then forSELECT column1
FROM t, the server sends back all the values forcolumn1using
the character set that the client specified when it connected. On the other hand, if you saySET
NAMES 'latin1'orSET CHARACTER SET latin1before
issuing theSELECTstatement,
the server converts thelatin2values tolatin1just
before sending results back. Conversion may be lossy if there are characters that are not in both character sets.
If you want the server to perform no conversion of result sets or error messages, setcharacter_set_resultstoNULLorbinary:
SET character_set_results = NULL;
To see the values of the character set and collation system variables that apply to your connection, use these statements:
SHOW VARIABLES LIKE 'character_set%';
SHOW VARIABLES LIKE 'collation%';
You must also consider the environment within which your MySQL applications execute. SeeSection10.1.5,
“Configuring the Character Set and Collation for Applications”.
For more information about character sets and error messages, seeSection10.1.6,
“Character Set for Error Messages”.
数据库的字符编码和表内字段的编码
在MySQL中数据库的字符编码和表内字段的编码的要指定为utf8(utf8_general_ci)
jsp中
pageEncoding="UTF-8"
request.setCharacterEncoding("UTF-8");
(十分重要)JDBC获取Connection时
设置url为jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
一般设置完前三步就基本没问题了。如果还不行,就修改mysql的配置文件吧。
MySQL配置文件 my.ini中
## UTF 8 Settings
#init-connect=\'SET NAMES utf8\'
#collation_server=utf8_unicode_ci
#character_set_server=utf8
#skip-character-set-client-handshake
#character_sets-dir="D:/xampp/mysql/share/charsets"
把前面的注释去掉。
重启MySQL,重启Tomcat。
以下为转载
charset 和 collation 有多个级别的设置:服务器级、数据库级、表级、列级和连接级
1.服务器级
查看设置:show global variables like 'character_set_server'; 和 show global variables like 'collation_server';
修改设置:在OPTION FILE (/etc/mysql/my.cnf)里设置:
[mysqld]
character_set_server=utf8
collation_server=utf8_general_ci
2. 数据库级
查看设置:select * from information_schema.schemata where schema_name = 'cookbook';
设置:
1.若没有显式设置,则自动使用服务器级的配置
2.显式设置:在创建库时指定
create database playUtf8 DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
3.表级
查看设置:show create table course;
设置:
1.若没有显式设置,则自动使用数据库级的配置
2.显式设置:在创建表时指定
create table utf ( id int ) default charset=utf8 default collate=utf8_bin;
4.列级
查看设置:show create table course;
设置:
1.若没有显式设置,则自动使用表级的配置
2.显式设置:
CREATE TABLE Table1(column1 VARCHAR(5) CHARACTER SET latin1 COLLATE latin1_german1_ci);
5.连接级别
查看设置:
show variables like 'character_set_client'; # 服务端使用这个编码来理解客户端发来的statements
show variables like 'character_set_connection' ; # 我还不知道什么意思,等看了mysql源码再说
show variables like 'character_set_results'; # 服务端使用这个编码回送结果集和错误信息
设置:
客户端在连接时可以指定这些参数;同时,服务端也提供了一个Global范围的值,客户端未指定这些参数时,服务端就使用这个Global值。这个global值怎么设置的? 我查遍了很多文档,似乎还没看到设置的办法 (有人说通过my.cnf,或者在启动mysqld时指定命令行参数,其实都是错的)
附:connector/j传输SQL时用什么编码?
答案: "The character encoding between client and server is automatically detected upon connection. The encoding used by the driver is specified on the server using the character_set_server system variable for server versions 4.1.0 and newer."
也就是说,是在连接时查询服务器端的character_set_server值,再确定连接将使用的编码。
不过,官方文档还说,"要想覆盖客户端上的自动检测编码功能,可在用于连接到服务器的URL中使用“characterEncoding”属性。"
版权声明:本文为博主原创文章,未经博主允许不得转载。
|