JDBC数据库操作之在数据库中获取指定时间段的数据

在数据库查询指定的时间段的数据记录

package JdbcTime;

import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 在数据库中获取指定范围的时间数据
 */
public class TestTime {
    /**
     * 将传入的字符串转为时间类型
     * @param str
     * @return
     */
    public static long strDate(String str){
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        try {
            long time = format.parse(str).getTime();
            return time;
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }
    public static void main(String[] args) {
        Connection con =null;
        PreparedStatement ps =null;
        ResultSet rs = null;
        try {
            //加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            //连接数据库
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123789");
            //预编译sql语句
            ps = con.prepareStatement("select * from user where lastlogtime >? and lastlogtime<?");
            //时间区域开始时间
            Timestamp start = new Timestamp(strDate("2019/5/1 13:13:13"));
            //时间区域结束时间
            Timestamp end = new Timestamp(strDate("2019/5/7 21:23:27"));
            //为第一个占位符设值
            ps.setTimestamp(1,start);
            //为第二个占位符设值
            ps.setTimestamp(2,end);
            //执行查询的sql语句并获得返回的结果集
            rs =ps.executeQuery();
            while (rs.next()){
                System.out.println(rs.getInt("uid")+"--"+rs.getString("uname")+"--"+rs.getTimestamp("lastlogtime"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

转载于:https://www.cnblogs.com/cqzy/p/10940707.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值