Questions And Answers

More Tutorials

postgreSQL Connect from Java


Connecting with java.sql.DriverManager

This is the simplest way to connect.

First, the driver has to be registered with java.sql.DriverManager so that it knows which class to use.

This is done by loading the driver class, typically with java.lang.Class.forname().

 * Connect to a PostgreSQL database.
 * @param url the JDBC URL to connect to; must start with "jdbc:postgresql:"
 * @param user the username for the connection
 * @param password the password for the connection
 * @return a connection object for the established connection
 * @throws ClassNotFoundException if the driver class cannot be found on the Java class path
 * @throws java.sql.SQLException if the connection to the database fails
private static java.sql.Connection connect(String url, String user, String password)
 throws ClassNotFoundException, java.sql.SQLException
 * Register the PostgreSQL JDBC driver.
 * This may throw a ClassNotFoundException.
 * Tell the driver manager to connect to the database specified with the URL.
 * This may throw an SQLException.
 return java.sql.DriverManager.getConnection(url, user, password);

Not that user and password can also be included in the JDBC URL, in which case you don't have to specify them in the getConnection method call.


In this page (written and validated by ) you learned about postgreSQL Connect from Java . What's Next? If you are interested in completing postgreSQL tutorial, your next topic will be learning about: postgreSQL Connecting with java sql DriverManager and Properties.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.