import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;public class MysqlTest { /** * @param args */ public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); //String url="jdbc:mysql://localhost:3306/mydb?user=******&password=******&useOldAliasMetadataBehavior=true&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false"; String url="jdbc:mysql://localhost:3306/mydb?user=******&password=******&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false"; Connection conn = DriverManager.getConnection(url); PreparedStatement stmt = conn.prepareStatement("select id as myid,name as myname from test"); ResultSet rs = stmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); String c1 = rsmd.getColumnName(1); String c2 = rsmd.getColumnName(2); while(rs.next()){ String id = rs.getString(c1);//报列名找不到异常 String name = rs.getString(c2); System.out.println(id+"|"+name); } System.out.println(conn); rs.close(); stmt.close(); conn.close(); }}
Exception in thread "main" java.sql.SQLException: Column 'id' not found. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872) at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1073) at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5212) at com.bill99.mysql.MysqlTest.main(MysqlTest.java:25)
解决办法:
JDBC URL中增加useOldAliasMetadataBehavior=true参数