JDBC连接数据库中文乱码问题

MrZhangxi 2016-10-23 11:19:58
写了一个JSP小程序,用JDBC把数据写入数据库,但是始终解决不了乱码问题,求大家帮助。代码贴出来
我JSP页面的编码用的使UTF-8,在网页上显示正常。
<%! String xuehao,name,gender,age,jiguan,yuanxi,url,user,pass; %>
<%! int xuehaoi, agei; %>
<%! Connection conn; %>
<%! ResultSet rs; %>
<%! PreparedStatement pstemt; %>
<%! String transForm(String str){
String newstr;
try{
newstr = new String(str.getBytes("iso8859-1"),"utf8");
} catch (Exception e) {
newstr = "编码转换发生了异常";
}
return newstr;
}%>

try{
if(request.getParameter("xuehao").trim()!=null && !"".equals(request.getParameter("xuehao").trim())){
xuehao = transForm(request.getParameter("xuehao").trim());
} else {
System.out.println("学号为空,跳转到错误页");
response.sendRedirect("err.jsp");
return;//这个return是跳出if语句的,下边的语句依然可达。如果在if外使用,就会使下边的代码不可达。
}

name = transForm(request.getParameter("name").trim());
gender = transForm(request.getParameter("gender").trim());
age = request.getParameter("age").trim();
jiguan = transForm(request.getParameter("jiguan").trim());
yuanxi = transForm(request.getParameter("yuanxi").trim());
} catch(Exception e){
System.out.println("没有拿到数据");
}

	try{
DataBaseUtils dbu = new DataBaseUtils();
dbu.intiDatabase();
url = "jdbc:mysql://localhost:3306/stumager";
user = "root";
pass = "";
conn = dbu.getconn(url, user, pass);
pstemt = conn.prepareStatement("insert into stu value(?,?,?,?,?,?)");
pstemt.setInt(1, xuehaoi);
pstemt.setString(2, name);
pstemt.setString(3, gender);
pstemt.setInt(4, agei);
pstemt.setString(5, jiguan);
pstemt.setString(6, yuanxi);
pstemt.execute();
response.sendRedirect("list.jsp");
} catch(Exception e){
System.out.println("数据库异常");
response.sendRedirect("err.jsp");
}

按照网上的方法修改了Mysql的编码,查询结果也贴出来
MariaDB [stumager]> show variables like "%char%";
+--------------------------+--------------------------------+
| Variable_name | Value |
+--------------------------+--------------------------------+
| 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:\xampp\mysql\share\charsets\ |
+--------------------------+--------------------------------+

但是结果还是乱码,写到数据的时,数据已经成了乱码。求解
...全文
268 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
_Kem 2016-10-23
  • 打赏
  • 举报
回复
url = "jdbc:mysql://localhost:3306/stumager?characterEncoding=UTF-8"; 这样估计就可以了
MrZhangxi 2016-10-23
  • 打赏
  • 举报
回复
我知道为什么了。因为我数据库编码是在DOS下用mysql命令设置的。这些设置应该是只在当前连接有效。在my.ini里边配置了一下就好了。default-character-set=utf8,这样配置如果启动不了的话就character-set-server=utf8
sinat_33072329 2016-10-23
  • 打赏
  • 举报
回复
数据库乱码解决无非检查三个问题。1.JSP文件首行有没指定为UTF8,2.有没在web.xml中指定编码过滤器,3楼上的已经说了url = "jdbc:mysql://localhost:3306/stumager?characterEncoding=UTF-8";

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧