获取列的名称(PostgreSQL)

时间:2011-10-18 11:44:12

标签: java sql postgresql

如何从PostgreSQL中的表中获取第一列的名称?

我知道如何解决这些问题,但我如何将第一个与其他人分开?

    public void getColumns(String username, String password, String database, String table){

        try {
            Class.forName("org.postgresql.Driver");
            String url = "jdbc:postgresql://localhost:5432/"+database;
            connection = DriverManager.getConnection(url, username, password);

            // Gets the metadata of the database
            DatabaseMetaData dbmd = connection.getMetaData();

            ResultSet rs = dbmd.getColumns(null, null, table, null);
                while (rs.next()) {
                    colummName = rs.getString("COLUMN_NAME");
                    System.out.println(colummName);
            }
        } catch (SQLException e) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if(connection!=null){

        } else {
            window.showNotification("Cannot connect to a Database",Notification.TYPE_WARNING_MESSAGE);
        }
    }

1 个答案:

答案 0 :(得分:2)

有点难以理解你在问什么,但我认为你想要一个给定索引的列名(在这种情况下,你想要第一列的名字)。

使用ResultSetMetaData

int index = 1; //for the first column
String columnName = rs.getMetaData().getColumnName(index);

请注意,列索引是从一开始的,而不是从零开始的。所以第一列是1,第二列是2等