PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] how to connect to PostgreSQL server to query the database names list

 April 21, 2022     connection, java, postgresql, sql     No comments   

Issue

I can use jdbc:postgresql://host:port/database to connect to a database in postgresql server using jdbc driver.

But I wanted to connect to the postgresql server and find the database list there. when I used jdbc:postgresql://localhost:5432, I got an exception called

java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432

is there any other driver or any method to get a connection to the server without knowing the database names in server and query the database list there?


Solution

Ok. I have figured it out my self. I can use this string to connect to the server with jdbc driver.

jdbc:postgresql://localhost:5432/?

and can use this code snippet to get the database list

private void listDownAllDatabases() {
        try {
            PreparedStatement ps = connection
                    .prepareStatement("SELECT datname FROM pg_database WHERE datistemplate = false;");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
            rs.close();
            ps.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

References: I used this dba stackexchange answer to get all the database list



Answered By - lakshman
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing