How to get the number of columns from a JDBC ResultSet?

前端 未结 5 965
旧巷少年郎
旧巷少年郎 2020-12-01 04:07

I am using CsvJdbc (it is a JDBC-driver for csv-files) to access a csv-file. I don\'t know how many columns the csv-file contains. How can I get the number of columns? Is th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 04:31

    Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

    //load the driver for PostgreSQL
    Class.forName("org.postgresql.Driver");
    
    String url = "jdbc:postgresql://localhost/test";
    Properties props = new Properties();
    props.setProperty("user","mydbuser");
    props.setProperty("password","mydbpass");
    Connection conn = DriverManager.getConnection(url, props);
    
    //create statement
    Statement stat = conn.createStatement();
    
    //obtain a result set
    ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");
    
    //from result set give metadata
    ResultSetMetaData rsmd = rs.getMetaData();
    
    //columns count from metadata object
    int numOfCols = rsmd.getColumnCount();
    

    But you can get more meta-informations about columns:

    for(int i = 1; i <= numOfCols; i++)
    {
        System.out.println(rsmd.getColumnName(i));
    }
    

    And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.

提交回复
热议问题