Java/Database SQL JDBC/Data Truncation

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

Get Data Truncation

   <source lang="java">

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

}

      </source>