|
3 | 3 | import java.sql.Connection; |
4 | 4 | import java.sql.DriverManager; |
5 | 5 |
|
6 | | - public class MyDatabaseConnection { |
7 | | - public static Connection getConnection() { |
8 | | - try { |
9 | | - String url = "jdbc:mysql://localhost:3306/testdbone"; |
10 | | - String userName = "root"; |
11 | | - String password = "asap5you"; |
12 | | - |
13 | | - Class.forName("com.mysql.cj.jdbc.Driver"); |
14 | | - Connection connection = DriverManager.getConnection(url, userName, password); |
15 | | - return connection; |
16 | | - }catch(Exception e) { |
17 | | - e.printStackTrace(); |
18 | | - } |
19 | | - return null; |
20 | | - } |
21 | | - public static void main(String[] args) { |
22 | | - Connection connection = getConnection(); |
23 | | - if(connection!=null) { |
24 | | - System.out.println("connection created"); |
25 | | - }else { |
26 | | - System.out.println("connection not created"); |
27 | | - } |
28 | | - } |
29 | | - } |
| 6 | +public class MyDatabaseConnection { |
30 | 7 |
|
| 8 | + public static Connection getConnection() { |
| 9 | + try { |
| 10 | + // Retrieve DB credentials from environment variables |
| 11 | + String url = System.getenv("DB_URL"); |
| 12 | + String username = System.getenv("DB_USER"); |
| 13 | + String password = System.getenv("DB_PASS"); |
31 | 14 |
|
| 15 | + // Validate credentials |
| 16 | + if (url == null || username == null || password == null) { |
| 17 | + throw new IllegalStateException( |
| 18 | + "Database credentials not set. Please configure DB_URL, DB_USER, DB_PASS as environment variables."); |
| 19 | + } |
| 20 | + |
| 21 | + // Establish database connection |
| 22 | + return DriverManager.getConnection(url, username, password); |
| 23 | + |
| 24 | + } catch (Exception e) { |
| 25 | + System.err.println("❌ Failed to connect to the database:"); |
| 26 | + e.printStackTrace(); |
| 27 | + return null; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + Connection connection = getConnection(); |
| 33 | + |
| 34 | + if (connection != null) { |
| 35 | + System.out.println("✅ Connection created successfully."); |
| 36 | + } else { |
| 37 | + System.out.println("❌ Connection not created."); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments