Home Tutorial Java Core JDBC: Get current TimeStamp Example

 
 

Share on Google+Share on Google+
JDBC: Get current TimeStamp Example
Posted on: September 28, 2012 at 12:00 AM
Advertisement
In this tutorial, we are going to describe how to get current TIMESTAMP using JDBC API.

JDBC: Get current TimeStamp Example

In this tutorial, we are going to describe how to get current TIMESTAMP using JDBC API.

Get current TimeStamp :

CURRENT_TIMESTAMP returns the current date and time .The TIMESTAMP data type provides automatic initialization and updating to the current date and time (that is, the current timestamp).
 It contains date and time information in the following format -
yyyy-mm-dd hh:mm:ss.[fff...]

 Example :  In this example we are using TimeStamp to display the current timestamp. we are using CURRENT_TIMESTAMP with select statement to display the current time stamp.

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class CurrentTimeStamp{
	public static void main(String[] args) {
	System.out.println("Current TimeStamp Example...");
	Connection con = null;
	Statement statement = null;
	ResultSet rs = null;
	String url = "jdbc:mysql://localhost:3306/";
	String dbName = "students";
	String driverName = "com.mysql.jdbc.Driver";
	String userName = "root";
	String password = "root";
	try {
		// Connecting to the database
		Class.forName(driverName);
		con = DriverManager.getConnection(url + dbName, userName, password);
		try {
			// Creating object of Statement
			statement = con.createStatement();

			// Get current TimeStamp
			String sql = "SELECT CURRENT_TIMESTAMP";
			rs = statement.executeQuery(sql);
			while (rs.next()) {
				System.out.println("Current TimeStamp : "+ rs.getTimestamp(1));
			}
		} catch (SQLException e) {
			System.out.println(e);
		}
		con.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
}

Output :

Current TimeStamp Example...
Current TimeStamp : 2012-09-28 15:44:21.0
Advertisement

Related Tags for JDBC: Get current TimeStamp Example:


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 28, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com