有java.sql.ResultSet
没有办法String
通过使用列的索引获取列的名称?我查看了API文档但我找不到任何东西.
您可以从ResultSet
元数据中获取此信息.请参见ResultSetMetaData
例如
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); String name = rsmd.getColumnName(1);
你可以从那里得到列名.如果你这样做
select x as y from table
然后rsmd.getColumnLabel()
也会得到检索到的标签名称.
除了上面的答案,如果您正在使用动态查询并且您想要列名但不知道有多少列,则可以使用ResultSetMetaData对象首先获取列数,然后循环它们.
修改Brian的代码:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); // The column count starts from 1 for (int i = 1; i <= columnCount; i++ ) { String name = rsmd.getColumnName(i); // Do stuff with name }
您可以使用ResultSetMetaData(http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html)对象,如下所示:
ResultSet rs = stmt.executeQuery("SELECT * FROM table"); ResultSetMetaData rsmd = rs.getMetaData(); String firstColumnName = rsmd.getColumnName(1);
这个问题很老,以前的答案也是正确的.但是当我发现这个话题时我正在寻找的就像这个解决方案.希望它可以帮助某人.
// Loading required libraries import java.util.*; import java.sql.*; public class MySQLExample { public void run(String sql) { // JDBC driver name and database URL String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/demo"; // Database credentials String USER = "someuser"; // Fake of course. String PASS = "somepass"; // This too! Statement stmt = null; ResultSet rs = null; Connection conn = null; VectorcolumnNames = new Vector (); try { // Register JDBC driver Class.forName(JDBC_DRIVER); // Open a connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute SQL query stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs != null) { ResultSetMetaData columns = rs.getMetaData(); int i = 0; while (i < columns.getColumnCount()) { i++; System.out.print(columns.getColumnName(i) + "\t"); columnNames.add(columns.getColumnName(i)); } System.out.print("\n"); while (rs.next()) { for (i = 0; i < columnNames.size(); i++) { System.out.print(rs.getString(columnNames.get(i)) + "\t"); } System.out.print("\n"); } } } catch (Exception e) { System.out.println("Exception: " + e.toString()); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception mysqlEx) { System.out.println(mysqlEx.toString()); } } } }
SQLite 3
使用getMetaData();
DatabaseMetaData md = conn.getMetaData(); ResultSet rset = md.getColumns(null, null, "your_table_name", null); System.out.println("your_table_name"); while (rset.next()) { System.out.println("\t" + rset.getString(4)); }
编辑:这也适用于PostgreSQL