-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemoJdbc.java
More file actions
59 lines (53 loc) · 2.07 KB
/
Copy pathDemoJdbc.java
File metadata and controls
59 lines (53 loc) · 2.07 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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Example: Proper Exception Handling in JDBC
*
* Concept:
* JDBC methods throw SQLException. Instead of just adding 'throws Exception'
* to the main method, we should catch SQLException to gracefully handle errors
* and ensure resources are closed in a finally block.
*
* Expected Output (if connection fails):
* Error code: 0
* SQL State: 08001
* Error message: Connection to localhost:5432 refused.
*/
public class DemoJdbc {
public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/java_jdbc";
String uname = "postgres";
String pass = "WRONG_PASSWORD"; // Intentional mistake
Connection con = null;
Statement st = null;
try {
// Establish connection
con = DriverManager.getConnection(url, uname, pass);
System.out.println("Connection established");
st = con.createStatement();
st.execute("SELECT * FROM non_existent_table"); // Intentional mistake
} catch (SQLException e) {
// This block handles JDBC-specific exceptions
System.err.println("Database Error occurred!");
System.err.println("Error code: " + e.getErrorCode());
System.err.println("SQL State: " + e.getSQLState());
System.err.println("Error message: " + e.getMessage());
} finally {
// The finally block ensures that resources are closed
// even if an exception occurs above.
try {
if (st != null) st.close();
} catch (SQLException e) {
System.err.println("Failed to close statement.");
}
try {
if (con != null) con.close();
} catch (SQLException e) {
System.err.println("Failed to close connection.");
}
System.out.println("Resources closed gracefully.");
}
}
}