JDBC_时间操作_时间段和日期段查询
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();
}
}
}
}
上一篇: 用java描述矩阵求逆的算法
下一篇: 数据表查询1