Не удается подключить базу данных к серверу
Не удалось подключить базу данных Postgres к серверу Tomcat 10.0.27. Вот код DBConnection:
public class DBConnection {
public static Connection getConnectionToDatabase() {
Connection connection = null;
try {
System.out.println("MySQL JDBC Driver Registered!");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
}
Вот код, где я пытаюсь получить соединение:
public class ApplicationDao {
public List<Product> searchProducts(String searchString) {
Product product = null;
List<Product> products = new ArrayList<>();
try{
Connection connection = DBConnection.getConnectionToDatabase();
String sql = "select * from products where product_name like '%"+searchString+"%'";
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while(set.next()){
product= new Product();
product.setProductId(set.getInt("product_id"));
product.setProductImgPath(set.getString("image_path"));
product.setProductName(set.getString("product_name"));
products.add(product);
}
}
catch(SQLException exception){
exception.printStackTrace();
}
return products;
}
}
Вот что я получаю:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Cannot invoke "java.sql.Connection.createStatement()" because "connection" is null
Я попытался отладить код, в логах появляется следующая ошибка:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message java.lang.ClassNotFoundException: com.example.jdbc.Driver
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.RuntimeException: java.lang.ClassNotFoundException: com.example.jdbc.Driver
com.example.demo.dao.DBConnection.getConnectionToDatabase(DBConnection.java:14)
com.example.demo.dao.ApplicationDao.searchProducts(ApplicationDao.java:19)
com.example.demo.servlets.SearchServlet.doGet(SearchServlet.java:30)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.ClassNotFoundException: com.example.jdbc.Driver
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1449)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1257)
java.base/java.lang.Class.forName0(Native Method)
java.base/java.lang.Class.forName(Class.java:383)
java.base/java.lang.Class.forName(Class.java:376)
com.example.demo.dao.DBConnection.getConnectionToDatabase(DBConnection.java:12)
com.example.demo.dao.ApplicationDao.searchProducts(ApplicationDao.java:19)
com.example.demo.servlets.SearchServlet.doGet(SearchServlet.java:30)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:683)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:792)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Добавил dependency в pom, также создал дирекорию lib в папке WEB-INF и добавил туда postgres.jar, также добавил postgres.jar в директорию tomcat/lib/, но ничего из вышеперечисленного не помогло
Источник: Stack Overflow на русском