Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How can we set time in a table in JDBC?
You can insert time values in SQL using the time datatype, The java.sql.Time class maps to the SQL Time type.
The PreparedStatement interface provides a method named setTime(). Using this you can insert time into a table. This method accepts two parameters −
An integer representing the parameter index of the place holder (?) to which we need to set date value.
A Time object representing the time value to be passed. The constructor of java.sql.Time class accepts a variable of long type representing the number of milliseconds from the epoch (standard base time I.e. January 1, 1970, 00:00:00 GMT).
Example
Assume we have created a table named Dispatches in MySQL database with the following description −
+------------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+---------+-------+ | Product_Name | varchar(255) | YES | | NULL | | | Date_Of_Dispatch | date | YES | | NULL | | | Time_Of_Dispatch | time | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +------------------+--------------+------+-----+---------+-------+
Following JDBC program inserts records in to this table −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Time;
import java.sql.Date;
public class InsertingTime {
public static void main(String args[])throws Exception {
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Inserting values to a table
String query = "INSERT INTO Dispatches VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "KeyBoard"); pstmt.setDate(2, new Date(1567296000000L));
pstmt.setTime(3, new Time(1567296000000L));
pstmt.setString(4, "Hyderabad");
pstmt.execute();
pstmt.setString(1, "Earphones"); pstmt.setDate(2, new Date(1556668800000L));
pstmt.setTime(3, new Time(1556668800000L));
pstmt.setString(4, "Vishakhapatnam");
pstmt.execute();
pstmt.setString(1, "Mouse"); pstmt.setDate(2, new Date(1551398399000L));
pstmt.setTime(3, new Time(1551398399000L));
pstmt.setString(4, "Vijayawada");
pstmt.execute();
System.out.println("Records inserted......");
}
}
Output
Connection established...... Records inserted......
