Get Data Truncation : Data Truncation « Database SQL JDBC « Java






Get Data Truncation

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();
    }
  }
}

           
       








Related examples in the same category