Меню Закрыть

Cannot load driver class org postgresql driver

Я работаю над веб-проектом, и я недавно установил postgres 9.1.1

Сервер postgresql запущен и работает. Я могу подключиться через psql, как обычно, и все загружено и правильно сохранено из дампа db, сделанного из 8.5.

Я добавил его в путь сборки java, используя свойства проекта через eclipse.

Это код, который я использую для обеспечения соединения db с другими классами (т.е. это singleton, я получаю новое соединение только в том случае, если существующее является либо закрытым, либо нулевым, из одного объекта за раз)

Как я писал в заголовке, когда я запускаю проект, а класс запрашивает подключение к этому классу, я всегда получаю исключение класса Not Found, так как он, по-видимому, не может загрузить org.postgresql.Driver.class. Драйвер находится в подпапке проекта

/lib/org.postgresql-9.1-901.jdbc4.jar и, как я уже сказал, добавлен в путь сборки через свойства проекта eclipse.

Я также предоставляю образец запроса, чтобы увидеть обычное поведение моих классов для доступа к DBConnection:

Я работаю над веб-проектом, и я недавно установил postgres 9.1.1

Я добавил его в путь сборки java , используя свойства проекта через eclipse.

Это неправильный путь. Этот JAR должен быть удален прямо в папке /WEB-INF/lib веб-проекта без использования пути сборки в свойствах проекта. Эта папка является стандартной частью пути к среде выполнения Webapp.

Несвязанный к конкретной проблеме: у вас есть главный недостаток дизайна в вашем классе DBConnection . Вы объявили Connection как static , который по существу делает ваше соединение не потокобезопасным. Используйте пул соединений и никогда не назначайте Connection (и Statement и ResultSet ) как переменную класса/экземпляра. Они должны быть созданы и закрыты в том же блоке try-finally , где вы выполняете запрос. Кроме того, у вас есть также инъекционное отверстие SQL. Используйте PreparedStatement вместо конкатенации контролируемых пользователем переменных в строке SQL.

Читайте также:  Мтс драйвер модель модема

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.

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)

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:

3 Answers 3

I’m working on a web project and I recently installed postgres 9.1.1

I added it to the java build path using the project properties via eclipse.

That’s the wrong way. That JAR has to be dropped straight in /WEB-INF/lib folder of the web project without fiddling with the Build Path in the project’s properties. That folder is standard part of webapp’s runtime classpath.

Unrelated to the concrete problem: you’ve a major design flaw in your DBConnection class. You’ve declared Connection as static which essentially makes your connection not threadsafe. Use a connection pool and never assign the Connection (nor Statement nor ResultSet ) as a class/instance variable. They should be created and closed in the very same try-finally block as where you’re executing the query. Further you’ve there also a SQL injection hole. Use PreparedStatement instead of concatenating user-controlled variables in the SQL string.

Читайте также:  Проверить серийный номер apple watch

Applications do not need to explicitly load the org.postgresql.Driver class because the pgjdbc driver jar supports the Java Service Provider mechanism. The driver will be loaded by the JVM when the application connects to PostgreSQL™ (as long as the driver’s jar file is on the classpath).

Prior to Java 1.6, the driver had to be loaded by the application — either by calling

or by passing the driver class name as a JVM parameter.

java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer

These older methods of loading the driver are still supported but they are no longer necessary.

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.