Data Truncation
From Java Example Source Code
Contents |
[edit] Overview - Data Truncation
This Java example program introduces how to use Data Truncation with JDBC.
[edit] Java Source Code
- Package: example.datatruncation
- File: DemoDataTruncation.java
package example.datatruncation; 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(); } } }
[edit] What Result You Can Get
Coming soon...
[edit] Required External Libraries and/or Files for this Java Example
In order to run this Java example, one of the following libraries may be required:
- MySQL JDBC driver. You can download it from MySQL Connector/J — for connecting to MySQL from Java
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
