方式一:設(shè)置編碼統(tǒng)一
1.設(shè)置eclipse環(huán)境編碼(推薦:java視頻教程)
2.設(shè)置mysql環(huán)境編碼
mydb為需要修改的數(shù)據(jù)庫(kù)名稱
方式二:創(chuàng)建數(shù)據(jù)庫(kù)時(shí)設(shè)置編碼
1.mysql創(chuàng)建database時(shí)設(shè)置編碼
create database mydb default character set utf8 collate utf8_general_ci;
2.創(chuàng)建表時(shí)設(shè)置編碼
CREATE TABLE `type` ( `id` int(10) unsigned NOT NULL auto_increment, `flag_deleted` enum('Y','N') character set utf8 NOT NULL default 'N', `flag_type` int(5) NOT NULL default '0', `type_name` varchar(50) character set utf8 NOT NULL default '', PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8;
方式三:連接數(shù)據(jù)庫(kù)時(shí)設(shè)置
在URL后添加?useUnicode=true&characterEncoding=UTF-8
public class TestJdbc { private static String URL = "jdbc:mysql://localhost:3306/studentmanage?useUnicode=true&characterEncoding=UTF-8"; useUnicode=true&characterEncoding=UTF-8 private static String USER = "root"; private static String PASSWORD = "root"; public static void main(String[] args) { Connection con = null; String sql = "insert into user(uid,uname,password) values(?,?,?)"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(URL, USER, PASSWORD); con.close(); } catch (Exception e) { e.printStackTrace(); } }
添加的作用是:指定字符的編碼、解碼格式。
例如:mysql數(shù)據(jù)庫(kù)用的是gbk編碼,而項(xiàng)目數(shù)據(jù)庫(kù)用的是utf-8編碼。這時(shí)候如果添加了useUnicode=true&characterEncoding=UTF-8 ,那么作用有如下兩個(gè)方面:
存數(shù)據(jù)時(shí):
數(shù)據(jù)庫(kù)在存放項(xiàng)目數(shù)據(jù)的時(shí)候會(huì)先用UTF-8格式將數(shù)據(jù)解碼成字節(jié)碼,然后再將解碼后的字節(jié)碼重新使用GBK編碼存放到數(shù)據(jù)庫(kù)中。
取數(shù)據(jù)時(shí):
在從數(shù)據(jù)庫(kù)中取數(shù)據(jù)的時(shí)候,數(shù)據(jù)庫(kù)會(huì)先將數(shù)據(jù)庫(kù)中的數(shù)據(jù)按GBK格式解碼成字節(jié)碼,然后再將解碼后的字節(jié)碼重新按UTF-8格式編碼數(shù)據(jù),最后再將數(shù)據(jù)返回給客戶端。