Java load postgresql driver

Class not found loading JDBC org.postgresql.Driver

I’m working on a web project and I recently installed postgres 9.1.1 The postgresql server is up and running. I can connect via psql as usual and everything is loaded and properly saved from a dump of the db I made from 8.5. So I also downloaded the JDBC4 driver for 9.1 postgres version here: http://jdbc.postgresql.org/download/postgresql-jdbc-9.1-901.src.tar.gz I added it to the java build path using the project properties via eclipse. This is the code I use to provide db connection to other classes (i.e. it’s a singleton, I get a new connection only if the existing is either closed or null, from one object at a time only)

public abstract class DBConnection < private static Connection connection = null; public static void connect() < try < if (connection == null) < String host = "127.0.0.1"; String database = "xxxxx"; String username = "xxxxx"; String password = "xxxxx"; String url = "jdbc:postgresql://" + host + "/" + database; String driverJDBC = "org.postgresql.Driver"; Class.forName(driverJDBC); connection = DriverManager.getConnection(url, username, password); //line firing the class not found exception >else if (connection.isClosed()) < connection = null; connect(); >> catch (SQLException e) < e.printStackTrace(System.err); >catch (Exception e) < e.printStackTrace(System.err); >> public static void disconnect() < if (connection != null) < try < connection.close(); >catch (SQLException e) < Logger.getLogger(DBConnection.class.getName()).log( Level.SEVERE, null, e); >> > public static Connection getConnection() < try < if (connection != null && !connection.isClosed()) < return connection; >else < connect(); return connection; >> catch (SQLException e) < Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, e); return null; >> @Override public void finalize() < if (connection != null) < try < connection.close(); >catch (SQLException e) < Logger.getLogger(DBConnection.class.getName()).log( Level.SEVERE, null, e); >> > > 

As I wrote in the title when I run the project and a class asks for a connection to this class I always get a Class Not Found Exception, Since it apparently can’t load the org.postgresql.Driver.class The driver is located in a subfolder of the project ~/lib/org.postgresql-9.1-901.jdbc4.jar and as I said added to the build path via eclipse project properties. I’m also providing a sample query to let see the usual behavior of my classes to access the DBConnection:

public static final User validateUserCredentials(String id, String pswd) < Connection connection = DBConnection.getConnection(); Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, (connection!=null)?"connection not null":"connection null"); Statement stmt = null; Logger.getLogger(Home.class.getName()).log(Level.SEVERE, "validating credentials for user: username : " + id + " password : " + pswd); String sql = "Select * from fuser where "; ResultSet resultset = null; try < stmt = connection.createStatement(); resultset = stmt.executeQuery(sql); Logger.getLogger(Credentials.class.getName()) .log(Level.SEVERE, sql); resultset.next(); String password = resultset.getString("pswd"); if (pswd.equals(password)) return new User(id, pswd); >catch (SQLException ex) < Logger.getLogger(Credentials.class.getName()).log(Level.SEVERE, null, ex); >finally < if (stmt != null) stmt = null; if (resultset != null) resultset = null; if (connection != null) < try < connection.close(); >catch (SQLException e) < >connection = null; > > return null; > 

Источник

Читайте также:  Http colt club ru forum index php

# 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.

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.

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.

Источник

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