java获取数据库数据的字符编码及转码

版权声明: https://blog.csdn.net/qq_36004521/article/details/81482867

1. 编写测试类

package com.hontye.parameter.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.*;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException, UnsupportedEncodingException {
    Test test = new Test();
    String URL="jdbc:mysql://192.168.1.102:3306/hontye_bh20180730";
    String USER="root";
    String PASSWORD="root";
    //1.加载驱动程序
	Class.forName("com.mysql.jdbc.Driver");
    //2.获得数据库链接
    Connection conn=DriverManager.getConnection(URL, USER, PASSWORD);
    //3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
    Statement st=conn.createStatement();
    String sql = "select concat(count(1),' 个') gs from ldar_model_ldpoint where sh_status ='4'";
    String encoder = test.getEncoding(sql);
    System.out.println("sql的字符编码:"+encoder);
    ResultSet rs=st.executeQuery(sql);
    //4.处理数据库的返回结果(使用ResultSet类)
	while(rs.next()){
        String s = rs.getString("gs");
        System.out.println("请求得到的值:"+s);
        System.out.println("字符编码为:"+test.getEncoding(s));
        System.out.println("utf-8格式为:" + URLEncoder.encode(s,"utf-8"));
        System.out.println("GBK格式为:" + URLEncoder.encode(s,"GBK"));
        System.out.println("ISO-8859-1格式为:" + URLEncoder.encode(s,"ISO-8859-1"));
        System.out.println("GB2312格式为:" + URLEncoder.encode(s,"GB2312"));
    }
    //5.关闭资源
	rs.close();
	st.close();
	conn.close();
}

    public String getEncoding(String str){

        String encoding = "GBK";
        try {
            if (str.equals(new String(str.getBytes(),encoding))) {
                return encoding;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        encoding = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(),encoding))) {
                return encoding;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        encoding = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(),encoding))) {
                return encoding;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        encoding = "GB2312";
        try {
            if (str.equals(new String(str.getBytes(),encoding))) {
                return encoding;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36004521/article/details/81482867