调试一简单JDBC连MySQL的程序,发现出现异常,导致连接无法成功,报错信息是:Unknown system variable 'language'
解决方案:在pom.xml里,将原有的版本降下来,我的就从5.1.36降低到了5.1.24
<!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.24</version> </dependency>
之后程序就运行正常了,代码如下:
package com.mq; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; public class Test { private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test"; private static final String USER = "root"; private static final String PSWD = "hy"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName(JDBC_DRIVER).newInstance(); conn = DriverManager.getConnection(DB_URL, USER, PSWD); stmt = conn.createStatement(); String sql = "select id,name,age from testtb order by id limit 10"; ResultSet rs = stmt.executeQuery(sql); int index = 0; while (rs.next()) { index++; String id = rs.getString("id"); String name = rs.getString("name"); String age = rs.getString("age"); String raw = "#{0},{1},{2},{3},{4}"; Object[] arr = { index, id, name, age }; String outStr = MessageFormat.format(raw, arr); System.out.println(outStr); } } catch (Exception e) { System.out.print("DB/SQL ERROR:" + e.getMessage()); } finally { try { stmt.close(); conn.close(); } catch (SQLException e) { System.out.print("Can't close stmt/conn because of " + e.getMessage()); } } } }
执行结果:
#1,1,andy,20,{4}
#2,2,bill,30,{4}
数据库里情况:
mysql> select * from testtb; +----+------+------+ | id | name | age | +----+------+------+ | 1 | andy | 20 | | 2 | bill | 30 | +----+------+------+ 2 rows in set (0.00 sec)
END