Recupera i nomi delle colonne da java.sql.ResultSet


233

Con java.sql.ResultSetc'è un modo per ottenere il nome di una colonna come a Stringusando l'indice della colonna? Ho dato un'occhiata al documento API ma non trovo nulla.

Risposte:


372

Puoi ottenere queste informazioni dai ResultSetmetadati. Vedi ResultSetMetaData

per esempio

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

e puoi ottenere il nome della colonna da lì. Se fate

select x as y from table

quindi rsmd.getColumnLabel()otterrai anche il nome dell'etichetta recuperata.


22
Vedi anche rsmd.getColumnLabelse recuperi colonne con etichette (ad esempioSELECT columnName AS ColumnLabel
— T30

15
Potresti essere sorpreso mentre vedo il conteggio delle colonne a partire da 1. Puoi scorrere i nomi delle colonne confor (int i = 1; i <= rsmd.getColumnCount(); i++) String name = rsmd.getColumnName(i);
— Alphaaa,

Non getColumnName()restituire il nome della colonna originale se non si utilizza ASl'alias di denominazione?
— membri del

2
@membersound Sì, come documentato nel suo Javadoc : "Se ASnon viene specificato un SQL , il valore restituito getColumnLabelsarà lo stesso del valore restituito dal getColumnNamemetodo." . In quasi tutti i casi dovresti usare getColumnLabelinvece di getColumnName.
— Mark Rotteveel,

1
Ciò fallirà se la tabella è vuota.
— andronix,

140

Oltre alle risposte sopra, se stai lavorando con una query dinamica e desideri i nomi delle colonne ma non sai quante colonne ci sono, puoi usare l'oggetto ResultSetMetaData per ottenere prima il numero di colonne e poi scorrere tra loro .

Modifica del codice di 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
}

non è vero? per (int i = 1; i <= columnCount + 1; i ++) {...}
— Martin

3
@Martin No, perché tenterà di ottenere la colonna n + 1 che non esiste. Se vuoi essere assolutamente conciso, lo sarebbe i <= columnCount.
— Cyntech,

21

È possibile utilizzare l'oggetto ResultSetMetaData ( http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html ) per questo, in questo modo:

ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);

1
grazie mi ha aiutato ... l'ho usato come: resultSet.getString (resultSet.findColumn ("fullname"))
— C Sharper

Limitare i record recuperati a 1. Altrimenti se la tabella è troppo grande, sovraccarico non necessario allora. Ad esempio per teradatabase: utilizzare la query "SELECT * FROM table SAMPLE 1"
— josepainumkal

11

Questa domanda è vecchia e così sono le risposte precedenti corrette. Ma quello che stavo cercando quando ho trovato questo argomento era qualcosa di simile a questa soluzione. Spero che aiuti qualcuno.

// 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;
    Vector<String> columnNames = new Vector<String>();

    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());
      }

    }
  }
}

5

SQLite 3

Utilizzo di 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));
}

EDIT: funziona anche con PostgreSQL


L'ho provato su un database teradata e ho ricevuto l'errore "[Database Teradata] [TeraJDBC 16.20.00.02] [Errore 9719] [SQLState HY000] La funzione QVCI è disabilitata."
— josepainumkal,

2
import java.sql.*;

public class JdbcGetColumnNames {

    public static void main(String args[]) {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/komal", "root", "root");

            st = con.createStatement();

            String sql = "select * from person";
            rs = st.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

            System.out.println("Table Name : " + metaData.getTableName(2));
            System.out.println("Field  \tDataType");

            for (int i = 0; i < rowCount; i++) {
                System.out.print(metaData.getColumnName(i + 1) + "  \t");
                System.out.println(metaData.getColumnTypeName(i + 1));
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Nome tabella: persona Campo Tipo di dati ID VARCHAR cname VARCHAR dob DATE


1

Quando hai bisogno dei nomi delle colonne, ma non vuoi afferrare le voci:

PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");

ResultSet set = stmt.executeQuery();

//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }

NOTA: funziona solo con MySQL


1
Solo questo ha funzionato per me !! Ho dovuto scendere per questo. Non so perché getColumnName (i) e getColumnLabel (i), mi hanno recuperato dati strani inaspettati. Grazie molto!
— VipiN Negi

Sono contento che questo ti abbia aiutato!
— Hunter S

1
while (rs.next()) {
   for (int j = 1; j < columncount; j++) {
       System.out.println( rsd.getColumnName(j) + "::" + rs.getString(j));      
   }
}

6
Per favore, puoi estendere la tua risposta con spiegazioni più dettagliate? Questo sarà molto utile per la comprensione. Grazie!
— Vezunchik,

1

Le istruzioni SQL che leggono i dati da una query del database restituiscono i dati in un set di risultati. L'istruzione SELECT è il modo standard per selezionare le righe da un database e visualizzarle in un set di risultati. L' **java.sql.ResultSet**interfaccia rappresenta il set di risultati di una query del database.

  • Ottieni metodi: usato per visualizzare i dati nelle colonne della riga corrente a cui punta il cursore.

utilizzando MetaData of a result set to fetch the exact column count

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);

http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html

e altro ancora per associarlo alla tabella del modello di dati

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    try {
        //STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to a selected database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Connected database successfully...");

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();

        String sql = "SELECT id, first, last, age FROM Registration";
        ResultSet rs = stmt.executeQuery(sql);
        //STEP 5: Extract data from result set
        while(rs.next()){
            //Retrieve by column name
            int id  = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            //Display values
            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        rs.close();
    } catch(SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch(Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if(stmt!=null)
                conn.close();
        } catch(SQLException se) {
        } // do nothing
        try {
            if(conn!=null)
                conn.close();
        } catch(SQLException se) {
            se.printStackTrace();
        } //end finally try
    }//end try
    System.out.println("Goodbye!");
}//end main
//end JDBCExample

tutorial molto bello qui: http://www.tutorialspoint.com/jdbc/

ResultSetMetaData meta = resultset.getMetaData();  // for a valid resultset object after executing query

Integer columncount = meta.getColumnCount();

int count = 1 ; // start counting from 1 always

String[] columnNames = null;

while(columncount <=count) {
    columnNames [i] = meta.getColumnName(i);
}

System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);

0

@Cyntech ha ragione.

Nel caso in cui la tabella sia vuota e sia ancora necessario ottenere i nomi delle colonne della tabella, è possibile ottenere la colonna come tipo Vector, vedere quanto segue:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

Vector<Vector<String>>tableVector = new Vector<Vector<String>>(); 
boolean isTableEmpty = true;
int col = 0;

 while(rs.next())
    {
      isTableEmpty = false;  //set to false since rs.next has data: this means the table is not empty
       if(col != columnCount)
          {
            for(int x = 1;x <= columnCount;x++){
                 Vector<String> tFields = new Vector<String>(); 
                 tFields.add(rsmd.getColumnName(x).toString());
                 tableVector.add(tFields);
             }
            col = columnCount;
          }
     } 


      //if table is empty then get column names only
  if(isTableEmpty){  
      for(int x=1;x<=colCount;x++){
           Vector<String> tFields = new Vector<String>(); 
           tFields.add(rsmd.getColumnName(x).toString());
           tableVector.add(tFields);
        }
      }

 rs.close();
 stmt.close();

 return tableVector; 

0
ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery(); 
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1

String nameValuePair = "";
while (rsTst.next()) {
    for (int i = 1; i < columnCount + 1; i++ ) {
        String name = meta.getColumnName(i);
        // Do stuff with name

        String value = rsTst.getString(i); //.getObject(1);
        nameValuePair = nameValuePair + name + "=" +value + ",";
        //nameValuePair = nameValuePair + ", ";
    }
    nameValuePair = nameValuePair+"||" + "\t";
}

0

Se si desidera utilizzare Spring jdbctemplate e non si desidera gestire il personale di connessione, è possibile utilizzare quanto segue:

jdbcTemplate.query("select * from books", new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            ResultSetMetaData rsmd = resultSet.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
                String name = rsmd.getColumnName(i);
                // Do stuff with name
            }
        }
    });

0

U può ottenere il nome e il valore della colonna da resultSet.getMetaData (); Questo codice funziona per me:

Connection conn = null;
PreparedStatement preparedStatement = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = MySQLJDBCUtil.getConnection();
        preparedStatement = conn.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
            }
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData md = resultSet.getMetaData();
            while (resultSet.next()) {
                int counter = md.getColumnCount();
                String colName[] = new String[counter];
                Map<String, Object> field = new HashMap<>();
                for (int loop = 1; loop <= counter; loop++) {
                    int index = loop - 1;
                    colName[index] = md.getColumnLabel(loop);
                    field.put(colName[index], resultSet.getObject(colName[index]));
                }
                rows.add(field);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            }catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    return rows;

0

Lo so, questa domanda ha già una risposta, ma probabilmente qualcuno come me deve accedere al nome di una colonna DatabaseMetaDatadall'etichetta anziché dall'indice:

ResultSet resultSet = null;
DatabaseMetaData metaData = null;

    try {
        metaData  = connection.getMetaData();
        resultSet = metaData.getColumns(null, null, tableName, null);

        while (resultSet.next()){
            String name = resultSet.getString("COLUMN_NAME");
        }
    }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.