import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* 时间操作--时间段查询和日期段
*/
public class TestTimeSelect {
/*
* 将字符串代表的日期转为long数字(格式:yyyy-MM-dd hh:mm:ss)
*/
public static long strDate(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/test","root","123456");
// ps = conn.prepareStatement("select * from user where date>? and date<?");
// java.sql.Date start = new java.sql.Date(strDate("2015-12-16 10:23:45"));
// java.sql.Date end = new java.sql.Date(strDate("2015-12-18 10:23:45"));
// ps.setObject(1, start);
// ps.setObject(2, end);
ps = conn.prepareStatement("select * from user where timestamp>? "
+ "and timestamp<? order by timestamp ");
Timestamp start = new Timestamp(strDate("2016-11-05 8:10:20"));
Timestamp end = new Timestamp(strDate("2016-11-05 9:9:10"));
ps.setObject(1, start);
ps.setObject(2, end);
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt("uid")+"--"+rs.getString("name")+
"--"+rs.getTimestamp("timestamp"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
8 时间操作--时间段查询和日期段
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。