How to connect postgresql to java

# Connect to PostgreSQL from Java

The API to use a relational database from Java is JDBC.

This API is implemented by a JDBC driver.

To use it, put the JAR-file with the driver on the JAVA class path.

This documentation shows samples how to use the JDBC driver to connect to a database.

# 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. */ Class.forName("org.postgresql.Driver"); /* * 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.

# Connecting with java.sql.DriverManager and Properties

Instead of specifying connection parameters like user and password (see a complete list here

(opens new window) ) in the URL or a separate parameters, you can pack them into a java.util.Properties object:

/** * 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. */ Class.forName("org.postgresql.Driver"); java.util.Properties props = new java.util.Properties(); props.setProperty("user", user); props.setProperty("password", password); /* don't use server prepared statements */ props.setProperty("prepareThreshold", "0"); /* * Tell the driver manager to connect to the database specified with the URL. * This may throw an SQLException. */ return java.sql.DriverManager.getConnection(url, props); > 

# Connecting with javax.sql.DataSource using a connection pool

It is common to use javax.sql.DataSource with JNDI in application server containers, where you register a data source under a name and look it up whenever you need a connection.

Читайте также:  Php warning stat failed

This is code that demonstrates how data sources work:

/** * Create a data source with connection pool for PostgreSQL connections * @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 data source with the correct properties set */ private static javax.sql.DataSource createDataSource(String url, String user, String password) < /* use a data source with connection pooling */ org.postgresql.ds.PGPoolingDataSource ds = new org.postgresql.ds.PGPoolingDataSource(); ds.setUrl(url); ds.setUser(user); ds.setPassword(password); /* the connection pool will have 10 to 20 connections */ ds.setInitialConnections(10); ds.setMaxConnections(20); /* use SSL connections without checking server certificate */ ds.setSslMode("require"); ds.setSslfactory("org.postgresql.ssl.NonValidatingFactory"); return ds; > 

Once you have created a data source by calling this function, you would use it like this:

/* get a connection from the connection pool */ java.sql.Connection conn = ds.getConnection(); /* do some work */ /* hand the connection back to the pool - it will not be closed */ conn.close(); 

# Remarks

The JDBC URL can take one of these forms:

**parameters** is a list of **key**[=**value**] pairs, headed by ? and separated by & . If the **value** is missing, it is assumed to be true .

jdbc:postgresql://localhost/test?user=fred&password=secret&ssl&sslfactory=org.postgresql.ssl.NonValidatingFactory 

Источник

Connecting To The PostgreSQL Database

Summary: in this tutorial, we will show you how to setup Java environment, download PostgreSQL JDBC driver, and connect to the PostgreSQL database server from a Java program.

Setting up Java development environment

To develop a Java program, you need to have JDK installed on your computer. To setup JDK, first, you go to the Oracle website to download the latest JDK. Then, you install it on your computer.

PostgreSQL JDBC Download JDK and NetBeans

The setup is straightforward, you just need to accept the default parameters provided the installer and you are set.

Practically, to develop java applications, you need to have a good IDE. There are many good IDE available for free such as Eclipse, NetBeans, IntelliJ IDEA Community Edition, etc.

In this tutorial, we will use the NetBeans IDE to develop Java application. You can download the NetBeans IDE directly from the Oracle website or you can download it from the NetBeans download page.

You can follow the steps as shown in the animated picture below to install the NetBeans IDE.

Download PostgreSQL JDBC Driver

To connect to the PostgreSQL database server from a Java program, you need to have PostgreSQL JDBC driver. You can download the latest version of the driver on the postgresql.org website via the download page.

The downloaded file is a jar file. You should copy it to a specific folder e.g. C:\demo\libs so that you can remember its location and be able to add it to your Java application later.

Читайте также:  Красивая карточка товара css

Connect to the PostgreSQL database server

First, create a new project named PostgreSQLJDBC and the main class named App in the com.postgresqltutorial package.

Second, add the PostgreSQL JDBC driver jar file to the project.

Third, you need to prepare the following:

  • The address of the PostgreSQL database server e.g., localhost
  • The database name e.g., dvdrental
  • The username and password of the account that you will use to connect to the database.

For this information, you can construct the PostgreSQL JDBC connection string by using the following format:

jdbc:postgresql://:/ Code language: SQL (Structured Query Language) (sql)

In our example, the connection string is:

jdbc:postgresql://localhost/dvdrentalCode language: SQL (Structured Query Language) (sql)

To make it easier, we can define the attributes of the App class for storing connection string, user, and password:

private final String url = "jdbc:postgresql://localhost/dvdrental"; private final String user = "postgres"; private final String password = "";Code language: Java (java)

To establish a connection to the PostgreSQL database server, you call the getConnection method of the DriverManager class. This method returns a Connection object.

The following connect() method connects to the PostgreSQL database server and returns a Connection object.

 public Connection connect() < Connection conn = null; try < conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to the PostgreSQL server successfully."); > catch (SQLException e) < System.out.println(e.getMessage()); >return conn; >Code language: Java (java)

The complete program for connecting to PostgreSQL database server is as follows:

package com.postgresqltutorial; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author postgresqltutorial.com */ public class App< private final String url = "jdbc:postgresql://localhost/dvdrental"; private final String user = "postgres"; private final String password = ""; /** * Connect to the PostgreSQL database * * @return a Connection object */ public Connection connect() < Connection conn = null; try < conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to the PostgreSQL server successfully."); > catch (SQLException e) < System.out.println(e.getMessage()); >return conn; > /** * @param args the command line arguments */ public static void main(String[] args) < App app = new App(); app.connect(); > > Code language: Java (java)

So we can connect to the PostgreSQL database server successfully.

In this tutorial, we have shown you how to setup the Java development environment for working with the PostgreSQL databases.

Источник

Java Connect to PostgreSQL database server with JDBC

This JDBC tutorial walks you through process of connecting a Java application to a PostgreSQL database server from downloading JDBC driver to write code that makes the connection. Before begin, make sure you have a version of PostgreSQL database server installed either on your development computer or on a dedicated server. Code in this tutorial is tested with PostgreSQL 9.1.

Table of content:

1. Download PostgreSQL JDBC driver

You can obtain the latest version of JDBC driver for PostgreSQL here. Currently there are two versions:

2. JDBC database URL for PostgreSQL

jdbc:postgresql: database

jdbc:postgresql: // host / database

jdbc:postgresql: // host : port / database

Читайте также:  Extract numbers in string java

jdbc:postgresql: // host : port / database?param1=value1&param2=value2&…

    • host : host name or IP address of the machine on which PostgreSQL server is running. If omitted, default is localhost.
    • port : port number on which the server is listening. If omitted, default is 5432.
    • database : name of the database to connect to.
    • param1=value1&param2=value2&…: specify additional connection parameters in pairs of key=value form. Most common parameters are user and password.

    — Connect to the database ProductDB on localhost:

    jdbc:postgresql:ProductDB

    — Connect to a remote PostgreSQL server on the host dbserver:

    jdbc:postgresql:dbserver:ProductDB

    — Using host name and port number explicitly:

    jdbc:postgresql:dbserver:5432:ProductDB

    — Specify user name and password for the connection:

    jdbc:postgresql:ProductDB&user=root&password=secret

    See all connection parameters specific to PosgreSQL.

    3. Register JDBC driver for PostgreSQL Server and create connection

    Class.forName("org.postgresql.Driver");
    DriverManager.registerDriver(new org.postgresql.Driver());

    However, since JDBC 4.0 (JDK 6.0 and later), the registration is not required. The JDBC driver manager can detect and load the appropriate driver when it is parsing the database URL.

    To establish a connection, call the method getConnection() of the DriverManager class and supply database URL and connection parameters. We can choose one in three versions of this method:

    — Version #1: getConnection(String url) . For example:

    String dbURL = "jdbc:postgresql:ProductDB?user=root&password=secret"; Connection conn = DriverManager.getConnection(dbURL);
    String dbURL = "jdbc:postgresql://localhost/ProductDB"; String user = "root"; String pass = "secret"; Connection conn = DriverManager.getConnection(dbURL, user, pass);
    String dbURL = "jdbc:postgresql://localhost:5432/ProductDB"; Properties parameters = new Properties(); parameters.put("user", "root"); parameters.put("password", "secret"); Connection conn = DriverManager.getConnection(dbURL, parameters);

    4. Java Code Example to connect to PostgreSQL database

    Following is a demo program which illustrates three different ways to make connections to a PostgreSQL server:

    package net.codejava.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * This program demonstrates how to make database connection to PostgreSQL * server using JDBC. * @author www.codejava.net * */ public class JdbcPostgresqlConnection < public static void main(String[] args) < // create three connections to three different databases on localhost Connection conn1 = null; Connection conn2 = null; Connection conn3 = null; try < // Connect method #1 String dbURL1 = "jdbc:postgresql:ProductDB1?user=root&password=secret"; conn1 = DriverManager.getConnection(dbURL1); if (conn1 != null) < System.out.println("Connected to database #1"); >// Connect method #2 String dbURL2 = "jdbc:postgresql://localhost/ProductDB2"; String user = "root"; String pass = "secret"; conn2 = DriverManager.getConnection(dbURL2, user, pass); if (conn2 != null) < System.out.println("Connected to database #2"); >// Connect method #3 String dbURL3 = "jdbc:postgresql://localhost:5432/ProductDB3"; Properties parameters = new Properties(); parameters.put("user", "root"); parameters.put("password", "secret"); conn3 = DriverManager.getConnection(dbURL3, parameters); if (conn3 != null) < System.out.println("Connected to database #3"); >> catch (SQLException ex) < ex.printStackTrace(); >finally < try < if (conn1 != null && !conn1.isClosed()) < conn1.close(); >if (conn2 != null && !conn2.isClosed()) < conn2.close(); >if (conn3 != null && !conn3.isClosed()) < conn3.close(); >> catch (SQLException ex) < ex.printStackTrace(); >> > >

    That’s how to connect a Java program to PostgreSQL database. To see the code in action, I recommend you to watch the video below:

    JDBC API References:

    About the Author:

    Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

    Источник

Оцените статью