sql
Handle SQL Exceptions example
This is an example of how to handle SQL Exceptions in Java. Handling SQL Exceptions implies that you should:
- Load the JDBC driver, using the
forName(String className)
API method of the Class. In this example we use the Oracle JDBC driver. - Create a Connection to the database. Invoke the
getConnection(String url, String user, String password)
API method of the DriverManager to create the connection. - Catch the SQLException and check the Exception message.
- Check the reason of the exception, the vendor-specific codes for the error and the SQLState for this SQLException, with
getMessage()
,getErrorCode()
,getSQLState()
API methods of SQLException. - In order to execute code based on the specific error code check the driver used for the JDBC connection. Get the DatabaseMetaData of the Connection, with
getMetaData()
API method of Connection and then the Driver name, withgetDriverName()
API method of DatabaseMetaData. - If the exception is chained process the next exception in the chain, with
getNextException()
API method of SQLException.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SQLException { public static void main(String[] args) { Connection connection = null; try { // Load the Oracle JDBC driver String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName); // Create a connection to the database String serverName = "localhost"; String serverPort = "1521"; String sid = "mySchema"; String url = "jdbc:oracle:thin:@" + serverName + ":" + serverPort + ":" + sid; String username = "username"; String password = "password"; connection = DriverManager.getConnection(url, username, password); System.out.println("Successfully Connected to the database!"); } catch (ClassNotFoundException e) { System.out.println("Could not find the database driver " + e.getMessage()); } catch (SQLException e) { while (e != null) { // the reason for the exception String message = e.getMessage(); // vendor-specific codes for the error int errorCode = e.getErrorCode(); String sqlState = e.getSQLState(); // To execute code based on the specific error code we should first check the driver used String driverName; try { driverName = connection.getMetaData().getDriverName(); if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) { // Process error specific to Oracle database ... } } catch (SQLException e1) { System.out.println("Could not retrieve database metadata " + e1.getMessage()); } // The exception may have been chained; process the next exception in the chain e = e.getNextException(); } } } }
Output:
Successfully Connected to the database!
This was an example of how to handle SQL Exceptions in Java.