欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JDBC_时间操作_时间段和日期段查询

程序员文章站 2024-01-11 10:27:04
import java.sql.Connection; import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;imp ......

import java.sql.connection;

import java.sql.drivermanager;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.sql.statement;
import java.sql.timestamp;
import java.text.dateformat;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.random;


/**
* 测试时间处理(java.sql.date,time,timestamp),取出指定时间段的数据
* @author 
*
*/
public class demo08 {

/**
* 将字符串代表的日期转为long数字(格式:yyyy-mm-dd hh:mm:ss)
* @param datestr
* @return
*/
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) {
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("2015-4-10 10:23:45"));
// java.sql.date end = new java.sql.date(str2date("2015-4-13 10:23:45"));
// ps.setobject(1, start);
// ps.setobject(2, end);

ps = conn.preparestatement("select * from t_user where lastlogintime>? and lastlogintime<? order by lastlogintime ");
timestamp start = new timestamp(str2date("2015-4-18 8:10:20"));
timestamp end = new timestamp(str2date("2015-4-18 9:9:10"));
ps.setobject(1, start);
ps.setobject(2, end);

rs = ps.executequery();
while(rs.next()){
system.out.println(rs.getint("id")+"--"+rs.getstring("username")+"--"+rs.gettimestamp("lastlogintime"));
}



} catch (classnotfoundexception e) {
e.printstacktrace();
} catch (sqlexception e) {
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();
}
}
}
}