What causes SQL exception? How it can be handled? Explain with example.

An SQLException in Java is thrown when something goes wrong with database access using JDBC (Java Database Connectivity).

🔥 Common causes include:

  1. Invalid database URL or credentials.
  2. Syntax errors in SQL queries.
  3. Trying to access non-existent tables/columns.
  4. Network issues between application and DB server.
  5. Trying to insert duplicate keys (violating constraints).
  6. Forgetting to close connections leading to resource exhaustion.

✅ How to Handle SQLException in Java

You can handle it using try-catch blocks and examine:

  • e.getMessage() → Describes the error.
  • e.getErrorCode() → Vendor-specific error code.
  • e.getSQLState() → SQL state as per ANSI SQL standard.

🧪 Example: Handling SQLException

import java.sql.*;

public class SQLExceptionExample {
    public static void main(String[] args) {
        Connection conn = null;

        try {
            // Load JDBC driver (optional in modern Java)
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Connect to database
            conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", "root", "wrongpassword"
            );

            // Execute a query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM non_existing_table");

        } catch (SQLException e) {
            System.out.println("SQLException occurred!");
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } catch (ClassNotFoundException e) {
            System.out.println("JDBC Driver not found: " + e.getMessage());
        } finally {
            // Close connection
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                System.out.println("Failed to close connection: " + e.getMessage());
            }
        }
    }
}

✅ Best Practices:

  • Always use try-with-resources to auto-close Connection, Statement, and ResultSet.
  • Log SQL exceptions properly.
  • Avoid revealing full SQL errors to users — use generic messages in production.

Post a Comment

Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.