Database tables you are interacting with can have the columns of Date type.
When you are inserting values into Date type column then you have to use the following
ps.setDate(3,dob);
When you are selecting values into Date type column then you have to use the following
Date dob= rs.getDate(3);
DB Work for Program
1) Create the following table
create table mystudents(
sid int primary key,
sname char(10),
dob date);
//package com.jtcindia.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Lab25 {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
int dd = 16;
int mm = 6;
int yy = 1979;
Date dob = new Date(yy - 1900, mm - 1, dd); // 1
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tutorial?autoReconnect=true&useSSL=false";
con = DriverManager.getConnection(url, "root", "root");
//con = DataSourceUtil.getConnection();
String SQL = "insert into mystudents values(?,?,?)";
ps = con.prepareStatement(SQL);
ps.setInt(1, 103);
ps.setString(2, "Somprakash");
ps.setDate(3, dob); // 2
int x = ps.executeUpdate();
System.out.println(x);
System.out.println("----Done-----");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DataSourceUtil.cleanUp(ps, con);
}
}
}
package com.jtcindia.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import com.coursecube.jdbc.util.DataSourceUtil;
public class Lab26 {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tutorial?autoReconnect=true&useSSL=false";
con = DriverManager.getConnection(url, "root", "root");
// con = DataSourceUtil.getConnection();
String SQL = "select * from mystudents";
ps = con.prepareStatement(SQL);
rs = ps.executeQuery();
while (rs.next()) {
int sid = rs.getInt(1);
String sname = rs.getString(2);
Date dob = rs.getDate(3); // 1
SimpleDateFormat spf = new SimpleDateFormat("dd-MMM-yyyy");
String mydob = spf.format(dob); // 2
System.out.println(sid + "\t" + sname + "\t" + mydob);
}
System.out.println("----Done-----");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DataSourceUtil.cleanUp(ps, con);
}
}
}