1. 程式人生 > >資料庫如何修改編碼格式?

資料庫如何修改編碼格式?

最近經常在群裡碰到問資料庫編碼格式怎麼修改的同學,這類的問題是老生常談的問題,也是在程式設計過程中經常讓人避之不及的問題。之前也被編碼格式問題搞過很多次,為了防止遇到同樣問題的人踩坑,故寫下這篇文章。
宣告:資料庫版本:MySQL5.6 開發軟體eclipse 語言:Java
首先要說的是在MySQL中修改編碼,如下:

  • 將具體表的編碼格式轉換為utf8:

     **alter table <表名> CONVERT TO CHARACTER SET utf8;**
    
  • 檢視資料庫編碼格式:

          **show variables 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);

%>
......(略)
  • 還有個比較奇葩的,在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響應到瀏覽器

2.解碼:(如果不進行解碼,頁面會獲取的是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);
    }
  }
}

這樣cookie就不會亂碼了。
更新:
在文字框中輸入中文,後臺通過JSP獲取到內容後返回到頁面出現亂碼:
在JSP頁面中的<body>下面寫上這段:

<%  request.setCharacterEncoding("utf-8"); %>