溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決

發(fā)布時間:2020-06-01 17:04:29 來源:PHP中文網(wǎng) 閱讀:228 作者:三月 欄目:編程語言

下文我給大家簡單講講關(guān)于java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決,大家之前了解過相關(guān)類似主題內(nèi)容嗎?感興趣的話就一起來看看這篇文章吧,相信看完java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決對大家多少有點(diǎn)幫助吧。                                                           java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決

方式一:設(shè)置編碼統(tǒng)一

1.設(shè)置eclipse環(huán)境編碼(推薦:java視頻教程)

java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決

2.設(shè)置mysql環(huán)境編碼

mydb為需要修改的數(shù)據(jù)庫名稱

java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決

方式二:創(chuàng)建數(shù)據(jù)庫時設(shè)置編碼

1.mysql創(chuàng)建database時設(shè)置編碼

create database mydb default character set utf8 collate utf8_general_ci;

2.創(chuàng)建表時設(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ù)庫時設(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ù)庫用的是gbk編碼,而項(xiàng)目數(shù)據(jù)庫用的是utf-8編碼。這時候如果添加了useUnicode=true&characterEncoding=UTF-8 ,那么作用有如下兩個方面:

存數(shù)據(jù)時:

數(shù)據(jù)庫在存放項(xiàng)目數(shù)據(jù)的時候會先用UTF-8格式將數(shù)據(jù)解碼成字節(jié)碼,然后再將解碼后的字節(jié)碼重新使用GBK編碼存放到數(shù)據(jù)庫中。

取數(shù)據(jù)時:

在從數(shù)據(jù)庫中取數(shù)據(jù)的時候,數(shù)據(jù)庫會先將數(shù)據(jù)庫中的數(shù)據(jù)按GBK格式解碼成字節(jié)碼,然后再將解碼后的字節(jié)碼重新按UTF-8格式編碼數(shù)據(jù),最后再將數(shù)據(jù)返回給客戶端。

大家覺得java插入mysql數(shù)據(jù)出現(xiàn)亂碼應(yīng)該如何解決這篇文章怎么樣,是否有所收獲。如果想要了解更多相關(guān),可以繼續(xù)關(guān)注我們的行業(yè)資訊板塊。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI