成功解决Tomcat-JDBC-MySQL乱码

MySQL-JDBC驱动文档官方解释

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 using Statement.execute(),Statement.executeUpdate()Statement.executeQuery() as well as all PreparedStatement andCallableStatement parameters with the exclusion of parameters set using setBytes()setBinaryStream(),setAsciiStream()setUnicodeStream() and setBlob().

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 in ResultSets.

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 theuseUnicode and characterEncoding properties.

Setting the Character Encoding

The character encoding between client and server is automatically detected upon connection. You specify the encoding on the server using the character_set_server for server versions 4.1.0 and newer, andcharacter_set system variable for server versions older than 4.1.0. The driver automatically uses the encoding specified by the server. For more information, see Section 10.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 leave characterEncoding out 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 the characterEncoding property 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 configuring utf8 as the default server character set, or by configuring the JDBC driver to use UTF-8 through the characterEncodingproperty.

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:

Table 22.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.

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 the character_set_client system 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 the character_set_connection and collation_connection system variables. It converts statements sent by the client from character_set_client to character_set_connection (except for string literals that have an introducer such as _latin1 or _utf8). collation_connection is important for comparisons of literal strings. For comparisons of strings with column values, collation_connection does 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?

    The character_set_results system 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 settings for 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 NAMES indicates 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 set cp1251. 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 a SELECT statement.)

    SET 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;
    

    Setting character_set_connection to charset_name also implicitly sets collation_connection to the default collation for charset_name. It is unnecessary to set that collation explicitly. To specify a particular collation, use the optional COLLATE clause:

    SET NAMES 'charset_name' COLLATE 'collation_name'
    
  • SET CHARACTER SET charset_name

    SET CHARACTER SET is similar to SET NAMES but sets character_set_connection andcollation_connection to character_set_database and collation_database. A SET CHARACTER SETcharset_name statement is equivalent to these three statements:

    SET character_set_client = charset_name;
    SET character_set_results = charset_name;
    SET collation_connection = @@collation_database;
    

    Setting collation_connection also implicitly sets character_set_connection to the character set associated with the collation (equivalent to executing SET character_set_connection = @@character_set_database). It is unnecessary to set character_set_connection explicitly.

Note

ucs2utf16, and utf32 cannot be used as a client character set, which means that they do not work for SET NAMES or SET CHARACTER SET.

The MySQL client programs mysqlmysqladminmysqlcheckmysqlimport, and mysqlshow determine the default character set to use as follows:

  • In the absence of other information, the programs use the compiled-in default character set, usually latin1.

  • The programs can autodetect which character set to use based on the operating system setting, such as the value of the LANG or LC_ALL locale 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, setting LANG to ru_RU.KOI8-R causes the koi8r character 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, ucs2 is not supported as a connection character set.

    C applications can use character set autodetection based on the OS setting by invoking mysql_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-set option, 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, usually latin1. An implication of this difference is that if your environment is configured to use a non-latin1 locale, MySQL client programs will use a different connection character set than previously, as though you had issued an implicit SET NAMES statement. If the previous behavior is required, start the client with the --default-character-set=latin1 option.

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 the character_set_clientcharacter_set_results, and character_set_connectionsystem variables. In effect, the server performs a SET NAMES operation using the character set name.

With the mysql client, to use a character set different from the default, you could explicitly execute SET NAMESevery time you start up. To accomplish the same result more easily, add the --default-character-set option setting to your mysql command line or in your option file. For example, the following option file setting changes the three connection-related character set variables set to koi8r each time you invoke mysql:

[mysql]
default-character-set=koi8r

If you are using the mysql client with auto-reconnect enabled (which is not recommended), it is preferable to use the charset command rather than SET NAMES. For example:

mysql> charset utf8
Charset changed

The charset command issues a SET NAMES statement, and also changes the default character set that mysqluses when it reconnects after the connection has dropped.

Example: Suppose that column1 is defined as CHAR(5) CHARACTER SET latin2. If you do not say SET NAMESor SET CHARACTER SET, then for SELECT column1 FROM t, the server sends back all the values for column1using the character set that the client specified when it connected. On the other hand, if you say SET NAMES 'latin1' or SET CHARACTER SET latin1 before issuing the SELECT statement, the server converts the latin2values to latin1 just 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, set character_set_results toNULL or binary:

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. See Section 10.1.5, “Configuring the Character Set and Collation for Applications”.

For more information about character sets and error messages, see Section 10.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”属性。" 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于 Tomcat 中的乱码问题,有几种可能的解决方法: 1. 设置 URIEncoding:在 Tomcat 的 server.xml 文件中,找到 <Connector> 元素,添加属性 URIEncoding="UTF-8",如下所示: ```xml <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" /> ``` 这样可以将 URI 请求的编码设置为 UTF-8,以防止乱码。 2. 设置默认字符集:在 web.xml 文件中,添加以下内容: ```xml <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 这样可以将请求和响应的字符集设置为 UTF-8。 3. 手动设置字符集:在处理请求或响应时,可以通过设置字符编码来解决乱码问题。例如,在 Servlet 中可以使用以下代码: ```java request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); ``` 4. 检查数据库连接字符集:如果使用了数据库,还需要确保数据库连接的字符集与应用程序一致。可以在数据库连接字符串中指定字符集,例如: ```java jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=UTF-8 ``` 这样可以将数据库连接的字符集设置为 UTF-8。 以上是一些常见的解决乱码问题的方法,根据具体情况选择适合的方法来解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值