时间类型
-
java.sql.Date 示年月日
-
java.sql.Time 表示时分秒
-
java.sql.Timestamp 表示年月日时分秒
日期比较处理
-
插入随机日期
-
取出指定日期范围的记录
Code
/**
* 测试事件处理(java.sql.Date,Time,Timestamp)
* @author Matrix42
*
*/
public class Demo07 {
public static void main(String[] args) throws InterruptedException {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","123456");
String sql = "insert into t_user(username,pwd,regTime,lastLoginTime) values(?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1, "Matrix42");
ps.setObject(2, 123456);
Date date = new java.sql.Date(System.currentTimeMillis());
ps.setObject(3, date);
//如果需要插入指定日期,可以使用Calendar,DateFormat类
ps.setTimestamp(4, new java.sql.Timestamp(System.currentTimeMillis()));
//随机日期
//int rand = 10000000 + new Random().nextInt(100000000);
//Timestamp stamp = new Timestamp(System.currentTimeMillis()-rand);
ps.execute();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
//关闭连接
}
}
/**
* 取出指定时间段的内容
* @author Matrix42
*
*/
public class Demo08 {
/**
* 将字符串代表的日趋转换为long(格式: yyyy-MM-dd hh:mm:ss)
* @param args
* @throws InterruptedException
*/
public static long str2Date(String dateStr){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
return format.parse(dateStr).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) throws InterruptedException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","123456");
ps = conn.prepareStatement("select * from t_user where regTime > ? and regTime < ?");
java.sql.Date start = new java.sql.Date(str2Date("2016-11-11 10:23:45"));
java.sql.Date end = new java.sql.Date(str2Date("2016-12-23 10:23:45"));
ps.setObject(1, start);
ps.setObject(2, end);
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("username"));
System.out.println(rs.getDate("regTime"));
System.out.println(rs.getTimestamp("lastLoginTime"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
//关闭连接
}
}