Home Tutorial Java Core Retrieve date from MYSQL database

 
 

Share on Google+Share on Google+
Retrieve date from MYSQL database
Posted on: September 20, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to retrieve date from database.

Retrieve date from MYSQL database

In this tutorial, you will learn how to retrieve date from database.

Storing and Retrieving dates from the database is a common task. MYSQL provides different ways of inserting and fetching dates from database. The dates saved in a database table is always in a proper format. The default format of date in MYSQL is YYYY-MM-DD.

Example

import java.sql.*;
import java.util.*;
import java.text.*;

public class RetrieveDate {
public static void main(String args[]) {
ResultSet rs = null;
Connection con = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("select dob from patient");
while (rs.next()) {

java.sql.Timestamp ts = rs.getTimestamp("dob");
java.sql.Date  date      = new java.sql.Date(ts.getTime());  
java.util.Date dd = new java.util.Date(date.getTime());
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(dd));
}
} catch (Exception e) {
e.printStackTrace();
} 
}
}

Description Of Code: In this example, we have created a database connection and using the Statement interface, we have send the SQL statement to the database. Here, we are going to retrieve the date of birth of persons from the database table. For this, we have used the TimeStamp class and Date class of java.sql package to fetch the dates from table and then we have converted those Date objects into a format using SimpleDateFormat class. The SimpleDateFormat is very efficient in giving a specified format to the date but it always formats the Date object of java.util package.

Advertisement

Related Tags for Retrieve date from MYSQL database:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 20, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com