• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

jdbc mysql 中文乱码的解决方法

mysql 搞代码 4年前 (2022-01-09) 34次浏览 已收录 0个评论

通过jdbc 连接mysql 数据库的实例,以及中文乱码的解决方法: import java.sql.*;/** * 使用JDBC连接数据库MySQL的过程: * DataBase: db_test * tables: tab_test; * username: user_test; * passwd: passwd_test; * * @author [email protected]

通过jdbc 连接mysql 数据库的实例,以及中文乱码的解决方法:

import java.sql.*;/** * 使用JDBC连接数据库MySQL的过程: * DataBase: db_test * tables:   tab_test; * username: user_test; * passwd:   passwd_test; * * @author  [email protected] */public class DBTest {  public static Connection getConnection() throws SQLException, ClassNotFoundException {    // 第一步:加载MySQL的JDBC的驱动    Class.forName("com.mysql.jdbc.Driver");    //取得连接的url,能访问MySQL数据库的用户名:user_test;密码:passwd_test, 数据库名: db_test    String url = "jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8";    String username = "user_test";    String password = "passwd_test";    // 第二步:创建与MySQL数据库的连接类的实例    Connection conn = DriverManager.getConnection(url, username, password);    return conn;  }  public static void main(String args[]) {    System.out.println("args num: " + args.length);    for (int i = 0; i < args.length; i++) {      System.out.println("arg " + i + ": " + args[i]);    }    Connection conn = null;    Statement statement = null;    try {      // 第三步:获取连接类实例<strong>本文来源gaodai#ma#com搞@@代~&码*网2</strong>con,用con创建Statement对象类实例 sql_statement      conn = getConnection();      statement = conn.createStatement();      /*      String sql_update = "insert into tab_test(province, num, timestamp) "        + "values('山东', 2, '2014-04-18 00:00:00');" ;      System.out.println(sql_update);      statement.executeUpdate(sql_update);      */      // 第四步:执行查询,用ResultSet类的对象,返回查询的结果      String query = "select * from tab_test;";      ResultSet result = statement.executeQuery(query);      while (result.next()) {        System.out.print(result.getInt(1) + " \t| ");        System.out.print(result.getString(2) + " \t| ");        System.out.print(result.getInt(3) + " \t| ");        System.out.println(result.getString(4));      }    } catch (ClassNotFoundException e) {      System.err.print("ClassNotFoundException: " + e.getMessage());      e.printStackTrace();      System.exit(1);    } catch (SQLException e) {      System.err.println("SQLException: " + e.getMessage());      e.printStackTrace();      System.exit(1);    } catch (Exception e) {      System.err.print("Exception: " + e.getMessage());      e.printStackTrace();      System.exit(1);    } finally { // release resources;      try {        if (statement != null) {          statement.close();          statement = null;        }        if (conn != null) {          conn.close();          conn = null;        }      } catch (SQLException e) {        System.err.println("SQLException: " + e.getMessage());        e.printStackTrace();        System.exit(1);      } catch (Exception e) {        System.err.println("Exception: " + e.getMessage());        e.printStackTrace();        System.exit(1);      }    }  }}

过,官方文档还说,”要想覆盖客户端上的自动检测编码功能,可在用于连接到服务器的URL中使用“characterEncoding”属性。”


解决方法二:

连接mysql时(无论在从mysql读还是取数据的情况),指定使用的编码方式为utf-8,具体代码如下

//装载mysql-jdbc驱动

Class.forName(“com.mysql.jdbc.Driver”).newInstance();

//连接数据库

Connection sqlCon = DriverManager.getConnection( “jdbc:mysql://localhost:3306/test? user=root&password=1&useUnicode=true&characterEncoding=utf-8” );

charset 和 collation 有多个级别的设置:服务器级、数据库级、表级、列级和连接级

1.服务器级
查看设置:show global variables like ‘character_set_server’; 和 show global variables like ‘collation_server’;
修改设置:在OPTION FILE (/etc/mysql/my.cnf)里设置:
[mysqld]
character_set_server=utf8
collation_server=utf8_general_ci

2. 数据库级
查看设置:select * from information_schema.schemata where schema_name = ‘cookbook’;
设置:
1.若没有显式设置,则自动使用服务器级的配置
2.显式设置:在创建库时指定
create database playUtf8 DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;

3.表级
查看设置:show create table course;
设置:
1.若没有显式设置,则自动使用数据库级的配置
2.显式设置:在创建表时指定
create table utf ( id int ) default charset=utf8 default collate=utf8_bin;

4.列级
查看设置:show create table course;
设置:
1.若没有显式设置,则自动使用表级的配置
2.显式设置:

CREATE TABLE Table1(column1 VARCHAR(5) CHARACTER SET latin1 COLLATE latin1_german1_ci);

5.连接级别
查看设置:
show variables like ‘character_set_client’; # 服务端使用这个编码来理解客户端发来的statements
show variables like ‘character_set_connection’ ; # 我还不知道什么意思,等看了mysql源码再说
show variables like ‘character_set_results’; # 服务端使用这个编码回送结果集和错误信息
设置:
客户端在连接时可以指定这些参数;同时,服务端也提供了一个Global范围的值,客户端未指定这些参数时,服务端就使用这个Global值。这个global值怎么设置的? 我查遍了很多文档,似乎还没看到设置的办法 (有人说通过my.cnf,或者在启动mysqld时指定命令行参数,其实都是错的)

附:connector/j传输SQL时用什么编码?
答案: “The character encoding between client and server is automatically detected upon connection. The encoding used by the driver is specified on the server using the character_set_server system variable for server versions 4.1.0 and newer.”
也就是说,是在连接时查询服务器端的character_set_server值,再确定连接将使用的编码。
过,官方文档还说,”要想覆盖客户端上的自动检测编码功能,可在用于连接到服务器的URL中使用“characterEncoding”属性。”


解决方法二:

连接mysql时(无论在从mysql读还是取数据的情况),指定使用的编码方式为utf-8,具体代码如下

//装载mysql-jdbc驱动

Class.forName(“com.mysql.jdbc.Driver”).newInstance();

//连接数据库

Connection sqlCon = DriverManager.getConnection( “jdbc:mysql://localhost:3306/test? user=root&password=1&useUnicode=true&characterEncoding=utf-8” );


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:jdbc mysql 中文乱码的解决方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址