Jdbc-exceptions

提供:Dev Guides
移動先:案内検索

JDBC-例外処理

例外処理を使用すると、プログラムで定義されたエラーなどの例外条件を制御された方法で処理できます。

例外条件が発生すると、例外がスローされます。 スローされるという用語は、現在のプログラムの実行が停止し、コントロールが最も近い該当するcatch句にリダイレクトされることを意味します。 適用可能なcatch句が存在しない場合、プログラムの実行は終了します。

JDBC例外処理はJava例外処理に非常に似ていますが、JDBCの場合、最も一般的な例外は* java.sql.SQLException。*です。

SQLExceptionメソッド

SQLExceptionは、ドライバーとデータベースの両方で発生する可能性があります。 このような例外が発生すると、SQLException型のオブジェクトがcatch句に渡されます。

渡されたSQLExceptionオブジェクトには、例外に関する追加情報を取得するために使用できる次のメソッドがあります-

Method Description
getErrorCode( ) Gets the error number associated with the exception.
getMessage( ) Gets the JDBC driver’s error message for an error, handled by the driver or gets the Oracle error number and message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception, or throwable, and it’s backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify.
printStackTrace(PrintWriter w) Prints this throwable and it’s backtrace to the print writer you specify.

Exceptionオブジェクトから入手可能な情報を利用することで、例外をキャッチしてプログラムを適切に続行できます。 ここにtryブロックの一般的な形式があります-

try {
  //Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
  //Your exception handling code goes between these
  //curly braces, similar to the exception clause
  //in a PL/SQL block.
}
finally {
  //Your must-always-be-executed code goes between these
  //curly braces. Like closing database connection.
}

*try .... catch ... finally* ブロックの使用方法を理解するには、次のコード例を検討してください。
//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
  //JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

  // Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   try{
     //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

     //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

     //STEP 4: Execute a query
      System.out.println("Creating statement...");
      Statement stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

     //STEP 5: Extract data from result set
      while(rs.next()){
        //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

        //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
     //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
     //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
     //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
     //finally block used to close resources
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample

さて、次のように上記の例をコンパイルしましょう-

C:\>javac JDBCExample.java
C:\>
*JDBCExample* を実行すると、問題がない場合は次の結果が生成されます。そうでない場合、対応するエラーがキャッチされ、エラーメッセージが表示されます-
C:\>java JDBCExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

間違ったデータベース名または間違ったユーザー名またはパスワードを渡して上記の例を試して、結果を確認してください。