Org postgresql driver error

A blog about Java, Programming, Algorithms, Data Structure, SQL, Linux, Database, Interview questions, and my personal experience.

java.lang.ClassNotFoundException: org.postgresql.Driver error comes when you are trying to connect to a PostgreSQL database from Java program but Java ClassLoader is not able to find the Driver class «org.postgresql.Driver» required to make the connection. Usually, this class is found in PostgreSQL JDBC driver jars like postgresql-9.4-1201.jdbc41.jar, which is required to connect the PostgreSQL server version greater than 9.3 from JDK 1.7 or JDK 1.8, the exact JAR depends upon your PostgreSQL server version, the Java version you are running, and JDBC version you are using.

Now your problem could be either you don’t have that PostgreSQL JDBC driver JAR in your machine or the JAR is not in your classpath, or you might be battling with some classpath intricacies.

If you don’t have this JAR, then a solution of «java.lang.ClassNotFoundException: org.postgresql.Driver» is simple, just download it from the PostgreSQL site. Make sure you download the correct version of the JDBC driver based upon the PostgreSQL server you are connecting and the JVM version of your machine.

Once you download that, just put in the lib directory of your Java application e.g. WEB-INF/lib if you are connecting to PostgreSQL from Java Web Application. If you are running in Tomcat, then you can alternatively also put this in tomcat/lib directory, but beware of the difference in the application dependency in WEB-INF/lib or in tomcat/lib.

You can also take a look at these JDBC Online Courses on Udemy. This course is a comprehensive guide on how to use JDBC in Java to connect to different databases. You will learn the right ways of doing things with respect to Java and the database.

Cause of java.lang.ClassNotFoundException: org.postgresql.Driver

In order to connect to the PostgreSQL database from Java, the first step is to register the driver with DriverManager. Generally, the Class.forName() method is used to find, load, and register JDBC driver. So if your application executes Class.forName(«org.postgresql.Driver»), then Java’s class loader tries to find this class in all the JAR files included in CLASSPATH.

If they are able to find then they load, instantiate and register the driver otherwise it throws java.lang.ClassNotFoundException: org.postgresql.Driver. Many times, what will happen that the JAR file will be there but you will still be getting java.lang.ClassNotFoundException: org.postgresql.Driver because of classpath mysteries, this is why I suggest you read my post, how ClassPath works in Java.

Sometimes, you add this JAR into the CLASSPATH environment variable, but your application would be running using -cp or -classpath option, so it will ignore the CLASSPATH environment variable. If that’s the case then you must include it in the -cp or -classpath option.

Some other times, like in the case of Servlet JSP based application, not putting the   JAR postgresql-9.4-1201.jdbc41.jar in WEB-INF/lib folder. This error is also exactly similar to java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver, which comes when you try to connect to Oracle database, and driver’s JAR is not in CLASSPATH. The steps and approaches mentioned there also apply to solve this problem.

Solution of java.lang.ClassNotFoundException: org.postgresql.Driver

Depending upon your setup, the solution could be any of these :

1) You need a PostgreSQL JDBC driver to connect from a Java program e.g. postgresql-9.4-1201.jdbc41.jar. Actual JDBC JAR could be different, depending upon the PostgreSQL server you are connecting and the Java version you are running. You can also download PostgreSQL driver from https://jdbc.postgresql.org/download.html

2) If you already have this JAR and your Java program is not running with -cp or -classpath option, then edit the CLASSPATH environment variable and add the directory, where you have put this JAR file. You can edit CLASSPATH in windows as set CLASSPATH = %CLASSPATH%; (location of PostgreSQL JDBC driver) and export CLASSPATH = ${CLASSPATH};postgresql-9.2-1002.jdbc3.jar

3) If your Java program is running with -cp or -classpath option then add the location of postgresql-9.2-1002.jdbc3.jar (PostgreSQL version 9.2 for Java version 1.6 or lesser with JDBC 3.0) as well e.g.
java -cp .;postgresql-9.2-1002.jdbc3.jar JavaToPostgreSQL, where JavaToPostgreSQL is name of your Java program. Remember separator in Windows is ; (Semi colon ) and separator in Linux is : (colon)

4) If you are connecting PostgreSQL db from Java Web application then put postgresql-9.4-1201.jdbc41.jar into your WEB-INF/lib folder, if your tomcat is running on Java 1.7 or 1.8 version.

5) If you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver i.e. postgresql-9.3-1103.jdbc3.jar. You can find the right version of the JDBC driver from the PostgreSQL site, depending upon the factors e.g. PostgreSQL version or Java version.

How to fix java.lang.ClassNotFoundException: org.postgresql.Driver in Java

That’s all about how to fix java.lang.ClassNotFoundException: org.postgresql.Driver error in Java. As I said, this error is very straightforward to solve, you just need the PostgreSQL JDBC driver in your CLASSPATH. The difficult thing is to understand how Classpath works, so make sure you read that tutorial.

A couple of other common errors and exceptions comes while connecting to other popular databases from Java programs like MySQL, Oracle, and Microsoft SQL Server

  • How to connect to MySQL database from Java Program [steps]
  • General Guide to solve java.lang.ClassNotFoundException in Java [guide]
  • How to solve java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver in Java? [solution]
  • How to fix java.lang.ClassNotFoundException: org.postgresql.Driver error in Java? [solution]
  • How to solve java.lang.ClassNotFoundException:org.Springframework.Web.Context.ContextLoaderListener [solution]
  • How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java MySQL? [solution]
  • java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory? [solution]
  • How to fix java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver in Java? [solution]

P. S. — If you already have the postgresql-9.2-1002.jdbc3.jar (or any other PostgreSQL JDBC driver) in classpath but still getting this error then please post in a comment what did you try and your setup e.g. CLASSPATH and we will try to troubleshoot together. In almost all cases its the CLASSPATH intricacies which cause «java.lang.ClassNotFoundException: org.postgresql.Driver».


0

1

Имеется spring-mvc проект. На локальной системе через mvn tomcat7:run запускается без проблем. При попытке деплоя на удаленный сервер (centos7/tomcat7 из репозитория) получаю следующее:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/datasource-tx-jpa.xml]: Invocation of init method failed; nested exce
<------>at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1634)
<------>at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
<------>at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
<------>at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
<------>at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
<------>at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
<------>at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:220)
<------>at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1018)
<------>at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:988)
<------>at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:579)
<------>at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546)
<------>at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:707)
<------>at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:680)
<------>at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
<------>at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
<------>at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354)
<------>... 76 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
<------>at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:396)
<------>at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371)
<------>at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336)
<------>at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1692)
<------>at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1630)
<------>... 91 more
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
<------>at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
<------>at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
<------>at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
<------>at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
<------>at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:69)
<------>at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:60)
<------>at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:40)
<------>at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:65)
<------>at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:59)
<------>at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:132)
<------>at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:61)
<------>at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:191)
<------>at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
<------>at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310)
<------>at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
<------>at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939)
<------>at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
<------>at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360)
<------>at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:384)
<------>... 95 more
Caused by: java.sql.SQLException: No suitable driver found for jdbc:postgresql://192.168.0.101/test
<------>at java.sql.DriverManager.getConnection(DriverManager.java:689)
<------>at java.sql.DriverManager.getConnection(DriverManager.java:208)
<------>at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
<------>at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
<------>at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196)
<------>at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:159)
<------>at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
<------>at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
<------>at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
<------>... 109 more

Конфиги одинаковые. В pom.xml прописан драйвер, пробовала разные версии, на десктопе работает, на сервере нет:

        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4.1212</version>
        </dependency>

jar вместе с другими зависимостями попадает в /lib каталог проекта:

[root@dev lib]# pwd
/usr/share/tomcat/webapps/ROOT/WEB-INF/lib
[root@dev lib]# find . -name "*postgresql*"
./postgresql-9.4.1212.jar
[root@dev lib]# 

В чем может быть проблема? Tomcat из репов centos привносит свою магию. Сначала билась над тем, что hibernate-validator шестой ветки с ним несовместим из-за старого tomcat-el, теперь вот это. Гуглёж ничего не дал.

  1. Не получается завести БД.
    При попытке коннекта получаю ошибку

    No suitable driver found for jdbc:postgresql://localhost:5432/postgres

    Не пойму что же я делаю не так

    String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
    this.connection = DriverManager.getConnection(url, user, password);
  2. Быстрая раскрутка сервера Minecraft


  3. Todorov26

    Todorov26
    Активный участник
    Пользователь

    Баллы:
    76
    Имя в Minecraft:
    Todorov26

    Ты к проекту подключил драйвер как либу? Если да, то Class.forName(путь к классу драйвера) кидает ошибку?

  4. Да и да. Тоже пробовал postgresql-42.2.10.jar и postgresql-42.3.1.jar подключать. При выполнении кода

    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    получаю ошибку
    java.lang.ClassNotFoundException: org.postgresql.Driver

  5. В ведре значит нету драйвера, таскай в плагине.

  6. Да, действительно, теперь я кажется стал понимать больше в том как это устроено.
    Тогда возникает такой вопрос, а как правильно в ИДЕЕ включить библиотеку в состав плагина?
    Как я уже понял недостаточно в проект добавить библиотеку, проект будет успешно компилироваться, но в состав jar файла плагина библиотека не войдёт.
    Я попробовал во вкладке «настройки проекта» -> «Артифакты» -> «выходной слой» перетащить jar файлы библиотек, но это не помогло, мне кажется они должны быть распакованными внутри плагина.

  7. Я вижу, что в других готовых плагинах есть папка META-INF в которой можно встретить файл java.sql.Driver


  8. Todorov26

    Todorov26
    Активный участник
    Пользователь

    Баллы:
    76
    Имя в Minecraft:
    Todorov26

    Юзать maven/gradle как вариант. Если не хочешь, то можешь попробовать кликнуть на настройку конфигураций, найти VM options и вставить туда Djava.library.path=путь до библиотеки. Сам не проверял ибо юзаю выше указаные сборщики.

  9. Да вы все усложняете, либо помещаешь классы либы в свой плагин, либо делаешь либу плагином, что даже удобней.


  10. Todorov26

    Todorov26
    Активный участник
    Пользователь

    Баллы:
    76
    Имя в Minecraft:
    Todorov26

    А смысл делать либу плагином? Я конечно давненько сделал плагин который всегда ставлю вместе со своими.
    Помещать классы все равно что делать лишнюю работу, ибо сборщик делает тоже самое по факту) Или я не прав?

  11. Что бы юзать с любым плагином, что требует эту либу. Логично нет? А не паковать ее в 90 плагинах.


  12. NuaN

    NuaN
    Активный участник
    Пользователь

    Баллы:
    96
    Имя в Minecraft:
    NuaN

    Еще как вариант — можно закинуть либу прямо в ядро

Поделиться этой страницей

Русское сообщество Bukkit

Bukkit по-русски - свой сервер Minecraft

Like this post? Please share to your friends:
  • Org openqa selenium webdriverexception unknown error failed to create chrome process
  • Org openqa selenium webdriverexception unknown error cannot find chrome binary
  • Org freedesktop dbus error spawn childexited
  • Org apache log4j logger error
  • Oracle ошибка 12705