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();
                }
            }
        }
    }
}

posted @ 2019-05-28 22:18  键盘敲坏  阅读(894)  评论(0编辑  收藏  举报