Java/Database SQL JDBC/SQL Warning

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

Determining If a SQL Warning Occurred

  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
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 {
      SQLWarning warning = connection.getWarnings();
      while (warning != null) {
        String message = warning.getMessage();
        String sqlState = warning.getSQLState();
        int errorCode = warning.getErrorCode();
        warning = warning.getNextWarning();
      }
      Statement stmt = connection.createStatement();
      warning = stmt.getWarnings();
      if (warning != null) {
      }
      ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
      while (resultSet.next()) {
        warning = resultSet.getWarnings();
        if (warning != null) {
        }
      }
    } catch (SQLException e) {
    }
  }
}





Get Next SQL Warning()

 
import java.sql.Connection;
import java.sql.DataTruncation;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
public class DemoDataTruncation {
  public static void displayError(DataTruncation dataTruncation) {
    System.out.println("Data truncation error: ");
    System.out.println(dataTruncation.getDataSize() + " bytes should have been ");
    if (dataTruncation.getRead()) {
      System.out.println("Read (Error:) ");
    } else {
      System.out.println("Written (Error:) ");
    }
    System.out.println(dataTruncation.getTransferSize()
        + " number of bytes of data actually transferred.");
  }
  public static void displayError(SQLWarning warning) {
    while (warning != null) {
      if (warning instanceof DataTruncation) {
        displayError((DataTruncation) warning);
      } else {
        System.out.println(" Warning: " + warning.getMessage());
      }
      warning = warning.getNextWarning();
    }
  }
  public static Connection getMySQLConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    String url = "jdbc:mysql://localhost/databaseName";
    String username = "root";
    String password = "root";
    Class.forName(driver);
    return DriverManager.getConnection(url, username, password);
  }
  public static void main(String[] args) throws Exception {
    Connection conn = getMySQLConnection();
    Statement stmt = null;
    try {
      stmt = conn.createStatement();
      stmt.executeUpdate("DELETE FROM animals_table");
      displayError(stmt.getWarnings());
      stmt.executeUpdate("INSERT INTO animals_table(id, name)"
          + "VALUES(1, "NameLongerThanColumnLengthInDatabase")");
      displayError(stmt.getWarnings());
    } catch (DataTruncation dt) {
      displayError(dt);
      dt.printStackTrace();
    } catch (SQLException se) {
      System.out.println("Database error message: " + se.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      stmt.close();
      conn.close();
    }
  }
}





Get SqlWarning Statement object

  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
public class SqlWarning {
  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
      String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
      Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
      Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      SQLWarning sw = null;
      ResultSet rs = stmt.executeQuery("Select * from employees");
      sw = stmt.getWarnings();
      System.out.println(sw.getMessage());
      while (rs.next()) {
        System.out.println("Employee name: " + rs.getString(2));
      }
      rs.previous();
      rs.updateString("name", "Jon");
    } catch (SQLException se) {
      System.out.println("SQLException occurred: " + se.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Raising Custom Sql Warning

 
import java.sql.SQLException;
import java.sql.SQLWarning;
public class RasingCustomSqlWarning {
  public static void main(String[] args) {
    try {
      throwWarning();
    } catch (SQLException e) {
      System.err.println("An SQL exception occurred: " + e);
      e.printStackTrace();
      while ((e = e.getNextException()) != null) {
        System.err.println("Contained reason: " + e);
      }
    }
  }
  private static void throwWarning() throws SQLException {
    SQLWarning rootWarning = new SQLWarning("Outter warning");
    SQLWarning containedWarning = new SQLWarning("Inner warning");
    rootWarning.setNextWarning(containedWarning);
    throw rootWarning;
  }
}