java串連資料庫讀取資料出現亂碼

來源:互聯網
上載者:User

標籤:註冊   manager   文字編碼   int   height   rom   rman   cat   string   

因為這是通用編碼,像中國通常使用的GBK、GB2312、Big5等只是針對中文而言,但是對其他文字就不適用了,為了使得這個問題的解決具有文字編碼通用性,所以我這裡設定了UTF8這個編碼。

編碼一致性涉及到的四個方面為:應用程式編碼、資料庫系統編碼、資料庫編碼、應用程式與資料庫系統的串連編碼。

1.mysql的設定,我的系統字元設定是拉丁文,也是夠夠的,發現之後要記得修改啊

 

 

2.java的設定,記得自己在剛開始的時候,設定的是:conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xsxx","root","123456");

這樣在儲存的時候,就會出現中文儲存的亂碼

 

其實,僅僅需要加上“?characterEncoding=utf8”就能夠實現中文的儲存。

運行效果如下:

 

3.代碼:

/*****
* java串連mysql
* @author yanlong
*2017/5/7
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
//import java.util.Collection;
import java.sql.SQLException;

//import javax.sql.Statement;

public class TestJDBC {
public static void main(String[] args){
ResultSet rs=null;
Statement stmt=null;
Connection conn=null;
try{
/*載入並註冊mysql的JDBC驅動*/
Class.forName("com.mysql.jdbc.Driver");
/*建立到mysql的串連*/

//conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xsxx","root","123456");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xsxx?characterEncoding=utf8","root","123456");
/*訪問資料庫,並執行sql語句*/

stmt=conn.createStatement();
/*添加記錄*/
System.out.println("添加記錄後:");
String sqll="insert into xs value (111111,‘小公舉‘,‘水利工程‘)";
stmt.executeUpdate(sqll);
rs=stmt.executeQuery("select * from xs");
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("name"));
System.out.println(rs.getString("major"));
}
rs=stmt.executeQuery("select *from xs");
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("name"));
System.out.println(rs.getString("major"));
}

}catch(ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e){
e.printStackTrace();

}
}
}
}

 

java串連資料庫讀取資料出現亂碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.