Get Column Names From ResultSet : Database « Servlets « Java






Get Column Names From ResultSet

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class GetColumnNamesFromResultSetMySQL {
  public static void getColumnNames(ResultSet rs) throws SQLException {
    if (rs == null) {
      return;
    }
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numberOfColumns = rsMetaData.getColumnCount();

    // get the column names; column indexes start from 1
    for (int i = 1; i < numberOfColumns + 1; i++) {
      String columnName = rsMetaData.getColumnName(i);
      // Get the name of the column's table name
      String tableName = rsMetaData.getTableName(i);
      System.out.println("column name=" + columnName + " table=" + tableName);
    }
  }

  public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    Statement stmt = null;
    ResultSet rs = null;

    String query = "select id, name, age from employees";
    stmt = conn.createStatement();
    rs = stmt.executeQuery(query);
    getColumnNames(rs);
    rs.close();
    stmt.close();
    conn.close();

  }

  public static Connection getMySqlConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    String url = "jdbc:mysql://localhost/octopus";
    String username = "root";
    String password = "root";

    Class.forName(driver); // load MySQL driver
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static Connection getOracleConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
    String username = "username";
    String password = "password";

    Class.forName(driver); // load Oracle driver
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

}
           
       








Related examples in the same category

1.Servlets Database Query
2.Using JDBC in Servlets
3.Cached Connection Servlet
4.Transaction Connection Servlet
5.Session Login JDBC
6.JDBC and Servlet
7.Database and Servlet: Database MetaData
8.Database and Servlet: Store procedure
9.Database transaction
10.Typical database commands
11.Process a raw SQL query; use ResultSetMetaData to format it
12.See Account
13.Guest Book Servlet
14.Dedicated Connection Servlet
15.Login Servlets
16.OCCI Connection Servlet
17.Display Clob Servlet
18.Delete Blob From Servlet
19.Delete Clob From Servlet
20.Display Blob Servlet
21.Delete Clob From Oracle in a Servlet
22.Insert Clob to MySql Servlet
23.Update Clob data stored in MySql from a Servlet