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();

}
}
}
}

 

posted @ 2017-05-09 12:15  glacial_water  阅读(13067)  评论(0编辑  收藏  举报
Document