-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.java
More file actions
39 lines (35 loc) · 1.34 KB
/
Copy pathDatabaseConnection.java
File metadata and controls
39 lines (35 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:postgresql://localhost:5432/food_ordering_system";
private static final String USERNAME = "postgres";
private static final String PASSWORD = "nthoond";
private static Connection connection = null;
public static Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Database connected successfully!");
}
} catch (ClassNotFoundException e) {
System.err.println("PostgreSQL JDBC Driver not found!");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("Connection failed!");
e.printStackTrace();
}
return connection;
}
public static void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}