Home >Database >Mysql Tutorial >java 连接 mysql 添加中文乱码_MySQL

java 连接 mysql 添加中文乱码_MySQL

WBOY
WBOYOriginal
2016-05-31 08:47:171116browse

bitsCN.com

java添加中文数据到mysql中,

包含中文就乱码 最初是想应该是由于字符编码不一致,所以查看数据库的属性跟表的属性

 查看表的字符集也是utf8,不是的改成自己想要设置的,我这里以utf8为例

 

所以查看mysql的编码 

#show variables like 'character%'

发现有几个编码格式不是utf8的, 修改 

 character_set_client  gbk 
 character_set_connection gbk
 character_set_database utf8
 character_set_filesystem binary
 character_set_results gbk
 character_set_server utf8

 character_set_system utf8

 character_sets_dir C:/Program Files/MySQL/MySQL Server 5.5/share/charsets/

将里面的编码格式改成

SET character_set_client='utf8';
SET character_set_connection='utf8';
SET character_set_results='utf8';  哪些不是就改哪,

也可以直接修改C:/Program Files/MySQL/MySQL Server 5.5/my.ini文

将里面的default-character-set改成utf8,注意是utf8,而不是utf-8,否则重启服务好像会报错1667错误,重启服务,再次查询编码,

#show variables like 'character%'

显示的

character_set_client utf8
character_set_connection utf8
character_set_database utf8
character_set_filesystem binary
character_set_results utf8
character_set_server utf8
character_set_system utf8
character_sets_dir C:/Program Files/MySQL/MySQL Server 5.5/share/charsets/
全是utf8了,当我再次往mysql加中文,这次不是乱码,程序中报错了,很纠结的事,

 Incorrect string value: '/xE8/xBF/x87/xE5/x88/x86...' for column 'username' at row 1

对此不熟悉碰了壁,但还是找到了答案,mysql中还能对表字段进行编码设置,

 show full columns from tablename,使用此命令可以查看表字段的字符编码

 如果你的Collation列中不是utf8,那么请修改

alter table 表 change 字段 字段 varchar(100) character set utf8 collate utf8_general_ci not null default '';  
下面是我对这张表的设置,

alter table user change username username varchar(100) character set utf8 collate utf8_general_ci not null default '';  
alter table user change password password varchar(100) character set utf8 collate utf8_general_ci not null default '';  
alter table user change nickname nickname varchar(100) character set utf8 collate utf8_general_ci not null default ''; 

这是我连接mysql的方式

 conn = DriverManager
     .getConnection(
       "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8",
       "username", "password");

 

添加中文成功了 

bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:2014/07/02 网站系统升级_MySQLNext article:MySQL安装