package com.lzy.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Demo06 {
public static long str2Date(String dateStr) {//把传入的日期转变为long型返回
DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
return format.parse(dateStr).getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
public static void main(String[] args) {
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("2020-11-15 12:12:12"));
java.sql.Date end=new java.sql.Date(str2Date("2020-11-21 12:12:12"));
ps.setObject(1, start);
ps.setObject(2, end);
rs=ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt("id")+"---"+rs.getString("username")+"----"+rs.getDate("regTime"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(ps!=null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC_时间操作_时间段和日期段查询
Java日期转换与数据库查询
最新推荐文章于 2023-09-15 22:41:12 发布
本文介绍了一个Java程序示例,该程序展示了如何将字符串格式的日期转换为long类型,并利用转换后的日期作为条件从数据库中查询特定时间段内的记录。
1162

被折叠的 条评论
为什么被折叠?



