Java/Database SQL JDBC/SQLException

Материал из Java эксперт
Версия от 06:35, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Get Error Code, SQL State, Message

  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlException {
  public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      String driver = "oracle.jdbc.driver.OracleDriver";
      Class.forName(driver).newInstance();
      System.out.println("Connecting to database...");
      String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
      conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
      stmt = conn.createStatement();
      try {
        rs = stmt.executeQuery("Select * from no_table_exisits");
      } catch (SQLException seRs) {
        String exMsg = "Message from MySQL Database";
        String exSqlState = "Exception";
        SQLException mySqlEx = new SQLException(exMsg, exSqlState);
        seRs.setNextException(mySqlEx);
        throw seRs;
      }
    } catch (SQLException se) {
      int count = 1;
      while (se != null) {
        System.out.println("SQLException " + count);
        System.out.println("Code: " + se.getErrorCode());
        System.out.println("SqlState: " + se.getSQLState());
        System.out.println("Error Message: " + se.getMessage());
        se = se.getNextException();
        count++;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Handling a SQL Exception: how to retrieve the information in a SQLException.

   
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);
    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
    try {
      connection.createStatement().execute("select wrong");
    } catch (SQLException e) {
      while (e != null) {
        String message = e.getMessage();
        String sqlState = e.getSQLState();
        int errorCode = e.getErrorCode();
        driverName = connection.getMetaData().getDriverName();
        if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) {
        }
        e = e.getNextException();
      }
    }
  }
}





Logging errors to a file

  
   
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.GregorianCalendar;
public class Logging {
  public static void main(String args[]) throws Exception {
    FileOutputStream errors = new FileOutputStream("StdErr.txt", true);
    PrintStream stderr = new PrintStream(errors);
    PrintWriter errLog = new PrintWriter(errors, true);
    System.setErr(stderr);
    String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con = DriverManager.getConnection("jdbc:odbc:Inventory");
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String name = rs.getString("Name");
        String desc = rs.getString("Description");
        int qty = rs.getInt("Qty");
        float cost = rs.getFloat("Cost");
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace(errLog);
    } catch (SQLException e) {
      System.err.println((new GregorianCalendar()).getTime());
      System.err.println("Thread: " + Thread.currentThread());
      System.err.println("ErrorCode: " + e.getErrorCode());
      System.err.println("SQLState:  " + e.getSQLState());
      System.err.println("Message:   " + e.getMessage());
      System.err.println("NextException: " + e.getNextException());
      e.printStackTrace(errLog);
      System.err.println();
    }
    stderr.close();
  }
}





Print the stack trace for a SQLException to STDERR.

 
import java.io.PrintWriter;
import java.sql.SQLException;
/* 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */
public class Main {

  /**
   * Print the stack trace for a SQLException to STDERR.
   *
   * @param e SQLException to print stack trace of
   */
  public static void printStackTrace(SQLException e) {
      printStackTrace(e, new PrintWriter(System.err));
  }
  /**
   * Print the stack trace for a SQLException to a 
   * specified PrintWriter. 
   *
   * @param e SQLException to print stack trace of
   * @param pw PrintWriter to print to
   */
  public static void printStackTrace(SQLException e, PrintWriter pw) {
      SQLException next = e;
      while (next != null) {
          next.printStackTrace(pw);
          next = next.getNextException();
          if (next != null) {
              pw.println("Next SQLException:");
          }
      }
  }
}