-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseConnection.java
More file actions
80 lines (70 loc) · 2.7 KB
/
Copy pathDatabaseConnection.java
File metadata and controls
80 lines (70 loc) · 2.7 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
package com.securefileshare.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/securefileshare";
private static final String USERNAME = "root";
private static final String PASSWORD = "durga2005";
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("MySQL JDBC Driver loaded successfully!");
} catch (ClassNotFoundException e) {
System.err.println("ERROR: MySQL JDBC Driver not found!");
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
System.out.println("Connecting to database...");
System.out.println("URL: " + URL);
System.out.println("Username: " + USERNAME);
try {
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Database connection successful!");
return conn;
} catch (SQLException e) {
System.err.println("ERROR: Database connection failed!");
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error Code: " + e.getErrorCode());
System.err.println("Message: " + e.getMessage());
throw e;
}
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) rs.close();
} catch (SQLException e) {
System.err.println("Error closing ResultSet: " + e.getMessage());
}
try {
if (ps != null) ps.close();
} catch (SQLException e) {
System.err.println("Error closing PreparedStatement: " + e.getMessage());
}
try {
if (conn != null) conn.close();
} catch (SQLException e) {
System.err.println("Error closing Connection: " + e.getMessage());
}
}
public static boolean testConnection() {
Connection conn = null;
try {
conn = getConnection();
return conn != null && !conn.isClosed();
} catch (SQLException e) {
System.err.println("Connection test failed: " + e.getMessage());
return false;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
}