/
houpsyu
/
Demo
Обзор
Документация
Войти
/
houpsyu
/
Demo
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/main/java/DatabaseConnection.java
48 строк
2 KB
demo
1
12 янв 2026, 17:48
12 янв 2026, 17:48
89b65aa
Код
Авторство
О чём код?
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { // Database URL, username, and password private static final String URL = "jdbc:postgresql://localhost:5432/test1"; private static final String USER = "postgres"; private static final String PASSWORD = "334455"; private static final String DRIVER = "org.postgresql.Driver"; // Static block to load the PostgreSQL JDBC driver static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { System.err.println("PostgreSQL JDBC driver not found."); e.printStackTrace(); } } // Method to establish a connection to the database public static Connection getConnection() throws SQLException { try { return DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { System.err.println("Failed to create connection to the database."); throw e; } } // Optional: Method to test the connection public static void testConnection() { try (Connection conn = getConnection()) { if (conn != null) { System.out.println("Successfully connected to the database!"); } } catch (SQLException e) { System.err.println("Database connection failed."); e.printStackTrace(); } } // Example usage public static void main(String[] args) { testConnection(); } }