![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yYzUjMxgDO5IjNzEzNzMTMyQ2Y0kTOyIDM1QDM2ATOz8CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
最近經常在群裡碰到問資料庫編碼格式怎麼修改的同學,這類的問題是老生常談的問題,也是在程式設計過程中經常讓人避之不及的問題。之前也被編碼格式問題搞過很多次,為了防止遇到同樣問題的人踩坑,故寫下這篇文章。
聲明:資料庫版本:MySQL5.6 開發軟體eclipse 語言:Java
首先要說的是在MySQL中修改編碼,如下:
- 将具體表的編碼格式轉換為utf8:
alter table <表名> CONVERT TO CHARACTER SET utf8;
- 檢視資料庫編碼格式:
ariables like 'character_set_database';
- 檢視資料表的編碼格式:
show create table <表名>;
- 建立資料庫時指定資料庫的字元集:
create database <資料庫名> character set utf8;
- 建立資料表時指定資料表的編碼格式:
create table tb_books (
name varchar(45) not null,
price double,
bookCount int,
author varchar(45)) default charset = utf8;
- 修改資料庫的編碼格式:
alter database <資料庫名> character set utf8;
- 修改字段編碼格式:
方法一:alter table <表名> change <字段名> <字段名> <類型> character set utf8;
方法二:alter table user change username username varchar(20) character set utf8 not null;
- 在JDBC連結資料庫時轉換編碼格式:
"jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF-8";
- 在接收頁面傳入的值時轉換編碼格式:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.net.URLDecoder" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=URLDecoder.decode(new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"),"UTF-8");
request.setAttribute("names", name);
%>
......(略)
- 在文本框中輸入中文,背景通過JSP擷取到内容後傳回到頁面出現亂碼:在JSP頁面中的
下面寫上這段:<body>
<% request.setCharacterEncoding("utf-8"); %>
- 還有個比較奇葩的,在cookie中儲存了中文,當選擇記住賬号密碼時,之前的中文竟然亂碼了。
-
這種情況,是因為它不怎麼支援中文,解決如下:
1.編碼:
将中文進行編碼再放入cookie中:
String username1 = URLEncoder.encode(username, "utf-8");
String userpwd1 = URLEncoder.encode(userpwd, "utf-8");
其中username和userpwd其中有中文,username1和userpwd1是進行編碼之後的字元串。 比如:(我這裡做的是三天免登陸) Cookie loginCookie = new Cookie("loginCookie",username1+":"+userpwd1);
//将編碼後的内容放到Cookie中
loginCookie.setMaxAge(24*3600);
//設定loginCookie的有效期3天 24小時*60分鐘*60秒
resp.addCookie(loginCookie);
//将loginCookie響應到浏覽器
解碼 :(如果不進行解碼,頁面會擷取的是base64編碼後的内容)
String unamePwd = URLDecoder.decode(cookies[i].getValue(),"utf-8");
其中cookies[i].getValue()是要進行解碼的内容,根據自己的情況進行修改。 我的代碼: //建立存放使用者名密碼的map
Map<String,String> loginMap = new HashMap<String,String>();
//擷取cookies
Cookie[] cookies = req.getCookies();
//進行判斷
if(cookies!=null) {
for(int i=0;i<cookies.length;i++) {
if(cookies[i].getName().equals("loginCookie")) {
String unamePwd = URLDecoder.decode(cookies[i].getValue(),"utf-8");
String[] up = unamePwd.split(":");
loginMap.put(up[0], up[1]);
req.getSession().setAttribute("loginMap",loginMap);
}
}
}