-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.java
More file actions
92 lines (84 loc) · 2.91 KB
/
Copy pathDatabaseConnection.java
File metadata and controls
92 lines (84 loc) · 2.91 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* DatabaseConnection.java - Manages MySQL database connections
*
* Handles:
* - Connection establishment
* - Driver loading
* - Connection pooling ready (can be extended with HikariCP)
* - Error handling
*
* Best Practice: Centralized connection management prevents code duplication
*/
public class DatabaseConnection {
// Database connection parameters
private static final String DB_URL = "jdbc:mysql://localhost:3306/library_management";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root"; // Change to your MySQL password
private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
// Connection timeout
private static final int CONNECTION_TIMEOUT = 30; // seconds
/**
* Static block to load MySQL driver at class loading time
* Throws exception if driver is not found
*/
static {
try {
Class.forName(DB_DRIVER);
System.out.println("✓ MySQL Driver loaded successfully");
} catch (ClassNotFoundException e) {
System.err.println("✗ MySQL Driver not found: " + e.getMessage());
System.err.println("Add mysql-connector-java JAR to classpath");
}
}
/**
* Gets a new database connection
*
* @return Connection object to MySQL database
* @throws SQLException if connection fails
*/
public static Connection getConnection() throws SQLException {
try {
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return conn;
} catch (SQLException e) {
System.err.println("✗ Database connection failed: " + e.getMessage());
throw new SQLException("Unable to connect to database", e);
}
}
/**
* Tests the database connection
* Useful for debugging connection issues
*
* @return true if connection successful, false otherwise
*/
public static boolean testConnection() {
try (Connection conn = getConnection()) {
if (conn.isValid(5)) { // 5 second timeout
System.out.println("✓ Database connection test passed");
return true;
}
} catch (SQLException e) {
System.err.println("✗ Connection test failed: " + e.getMessage());
}
return false;
}
/**
* Closes a database connection safely
* Handles null connection gracefully
*
* @param conn Connection to close
*/
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
}
}