-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyDatabaseConnection.java
More file actions
40 lines (32 loc) · 1.27 KB
/
MyDatabaseConnection.java
File metadata and controls
40 lines (32 loc) · 1.27 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
package Task9;
import java.sql.Connection;
import java.sql.DriverManager;
public class MyDatabaseConnection {
public static Connection getConnection() {
try {
// Retrieve DB credentials from environment variables
String url = System.getenv("DB_URL");
String username = System.getenv("DB_USER");
String password = System.getenv("DB_PASS");
// Validate credentials
if (url == null || username == null || password == null) {
throw new IllegalStateException(
"Database credentials not set. Please configure DB_URL, DB_USER, DB_PASS as environment variables.");
}
// Establish database connection
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.err.println("❌ Failed to connect to the database:");
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
Connection connection = getConnection();
if (connection != null) {
System.out.println("✅ Connection created successfully.");
} else {
System.out.println("❌ Connection not created.");
}
}
}