jdbc串連FreeBsd上的mysql資料庫中文發生亂碼的解決辦法

來源:互聯網
上載者:User

在FreeBSD上安裝資料庫的時候沒有把gbk安裝上去,結果從windows系統上備份過來的mysql資料庫不能匯入到freebsd的mysql上,尋找問題,結果是windows上採用的是gb2312的編碼方式而在freebsd上的mysql卻沒有這種編碼方式,只能開啟Windows上的備份檔案修改其中的DEFAULT CHARACTER SET gb2312修改成utf8這樣才能把檔案匯入到freebsd的mysql中。

匯入完畢後用ECLIPSE作了一個小程式用jdbc串連mysql中的資料庫。結果發現是亂碼。

在freebsd系統下查看mysql的status

mysql> status;
--------------
mysql  Ver 14.7 Distrib 4.1.18, for portbld-freebsd6.1 (i386) using  5.0

Connection id:          52
Current database:       schoolmis
Current user:           root@localhost
SSL:                    Not in use
Current pager:          more
Using outfile:          ''
Using delimiter:        ;
Server version:         4.1.18-log
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    latin1
Conn.  characterset:    latin1
UNIX socket:            /tmp/mysql.sock
Uptime:                 1 hour 17 min 51 sec

Threads: 2  Questions: 494  Slow queries: 0  Opens: 44  Flush tables: 1  Open tables: 19  Queries per second avg: 0.106
--------------
原來MySQL的預設編碼了,一般不調整的話為latin1其實和ISO8859_1一樣,所以在讀取這些字元的時候要進行處理否則就會產生亂碼

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   Connection con = DriverManager
     .getConnection("jdbc:mysql://10.33.250.2/schoolmis?user=sa&password=sa&useUnicode=true&characterEncoding=utf8");
   Statement stmt = con.createStatement();
 //  String strSQL="insert into student values('長城')";
 //  stmt.executeUpdate(strSQL);
 //  stmt.close();
    stmt = con.createStatement();
   ResultSet rs = stmt.executeQuery("select * from  ");
   while (rs.next()) {
     String str=new String(rs.getString("studentid").getBytes("ISO8859_1"),"GBK");
      System.out.println(str);

   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
另外一種方式

 當然在MySQL為latin1編碼時,也可以存的時候用GBK了
Connection con=DriverManager.getConnection("jdbc:mysql://10.33.250.2:3306/user=sa&password=sa?useUnicode=true&characterEncoding=GBK"); 
  Connection con = DriverManager
     .getConnection("jdbc:mysql://10.33.250.2/schoolmis?user=sa&password=sa&useUnicode=true&characterEncoding=utf8");
   Statement stmt = con.createStatement();
 String strSQL="insert into student values('長城')";
   stmt.executeUpdate(strSQL);
   stmt.close();

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.