How to Get Date, Time & Timestamp Data from MySQL
From Java Example Source Code
Contents |
[edit] Overview - How to Get Date, Time & Timestamp Data from MySQL
This Java example program shows how to get Date, Time & Timestamp data from MySQL with JDBC.
[edit] Java Source Code
- Package: example.datetimetimestamp
- File: GetDateFromMySql.java
package example.datetimetimestamp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class GetDateFromMySql { 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[]) { ResultSet rs = null; Connection conn = null; Statement stmt = null; try { conn = getMySQLConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("select timeCol, dateCol, dateTimeCol from dateTimeTable"); while (rs.next()) { java.sql.Time dbSqlTime = rs.getTime(1); java.sql.Date dbSqlDate = rs.getDate(2); java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3); System.out.println("dbSqlTime=" + dbSqlTime); System.out.println("dbSqlDate=" + dbSqlDate); System.out.println("dbSqlTimestamp=" + dbSqlTimestamp); java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime()); java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime()); System.out.println("in standard date"); System.out.println(dbSqlTimeConverted); System.out.println(dbSqlDateConverted); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
[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.
