问题描述
MySQL默认编码是latin1,使用MySQL客户端(Navcat for MySQl或MySQL client)插入中文数据,内容显示正常,但使用Java程序插入中文数据出现中文乱码(问号)。
mysql> show variables like 'character%';
+--------------------------+----------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | D:\mysql\mysql-5.6.27-winx64\share\charsets\ |
+--------------------------+----------------------------------------------+
mysql> create table `messages` (
-> `id` int(4) not null,
-> message varchar(50) not null
-> ) engine=myisam default charset=utf8;
Query OK, 0 rows affected
mysql> insert into messages (message) values ("测试MySQL中文显示");
Query OK, 1 row affected
mysql> select * from messages;
+----+-------------------+
| id | message |
+----+-------------------+
| 0 | 测试MySQL中文显示 |
+----+-------------------+
1 row in set
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCTest {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into messages (message) values ('测试MySQL编码')");
ResultSet rs = stmt.executeQuery("select * from messages");
while (rs.next()) {
int id = rs.getInt("id");
String message = rs.getString("message");
System.out.println(id + " " + message);
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序输出
1 ????MySQL????????
2 ??MySQL??
问题解决
我们看到,尽管使用数据库是我们能够正常添加和显示中文,但是在使用java程序链接数据库时并不能正常显示中文,为此我们需要修改MYSQL的默认编码,编辑my.ini
(MySQL配置文件)对默认编码进行修改,设置MySQL的默认字符集为utf8:
找到客户端配置[client]
在下面添加:
default-character-set=utf8
找到服务配置[mysqld]
在下面添加:
default-character-set=utf8
设定MySQL数据库以utf8编码运行,连接MySQL数据库时使用utf8编码。重启MySQl服务
windows
net stop mysql
net start mysql
linux
service mysqld restart
常见问题
在修改配置文件之后,可能存在mysql无法启动的意外情况;原因可能是出在了MySQL版本问题,试着修改如下写法:
character-set-server=utf8