java連接數據庫讀取數據出現亂碼


因為這是通用編碼,像中國通常使用的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();

}
}
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM