当前位置: 移动技术网 > IT编程>开发语言>Java > JDBC_时间操作_时间段和日期段查询

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

2019年03月01日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网