1. 程式人生 > >java語言利用MySQL資料庫自帶的DATE_SUB()函式查詢一週、一個月、半年、一年之內的資料記錄

java語言利用MySQL資料庫自帶的DATE_SUB()函式查詢一週、一個月、半年、一年之內的資料記錄

在JSP頁面中根據論壇帖子的發帖時間查詢帖子記錄,前臺JSP頁面程式碼如下:

<s:form id="postTime" action="findPostByTime" method="post" theme="simple" target="mFrame">
	<table class="tab_data" width="70%" >
		<tr>
			<td class="left" width="30%">
				請選擇時間:
			</td>
			<td width="70">
			<s:select name="postTime" list="#{'最近一週':'最近一週','最近半個月':'最近半個月','最近一個月':'最近一個月','最近半年':'最近半年','最近一年':'最近一年'}" listKey="value"	listValue="key" theme="simple" headerKey="-1"	headerValue="—發帖時間—">
			</s:select>
			</td>
				
		</tr>
			
			
		<tr>
			<td	class="right" colspan="2" >
			<span style="white-space:pre">	</span><div align="center">
				    <s:submit  value="查詢" theme="simple" cssClass="btn_normal" />
					 
				</div>
			</td>
			
		</tr>
	</table>
</s:form>


後臺的java程式碼如下:

private List<McpForumPost> forumPostList;      
private String postTime;  		//類的私有成語變數及其get()和set()方法
public String getPostTime() {
	return postTime;
}


public void setPostTime(String postTime) {
	this.postTime = postTime;
}
public List<McpForumPost> getForumPostList() {
	return forumPostList;
}


public void setForumPostList(List<McpForumPost> forumPostList) {
	this.forumPostList = forumPostList;
}
            /**
		 * 
		 * 前臺jsp頁面傳入一個String型別的postTime,根據發帖時間查詢帖子
		 * **/

public String findPostByTime() {
System.out.println(postTime);		
private String columnSql = "select a.post_id,a.user_id,a.board_id,a.post_title,a.post_time,a.check_state,a.is_top,a.is_good,a.post_state,b.account from mcp_forum_post as a,scpn_user as b ";			
 String sql_fy;
try {		
//其中post_time在MySQL資料庫中以datetime型別儲存
if(postTime.equals("最近一週")){
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 and a.post_time>DATE_SUB(CURDATE(), INTERVAL 7 DAY)" ;					
}else if(postTime.equals("最近半個月")){
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 and a.post_time>DATE_SUB(CURDATE(), INTERVAL 15 DAY)";					
}else if(postTime.equals("最近一個月")){
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 and a.post_time>DATE_SUB(CURDATE(), INTERVAL 1 MONTH)";
}else if(postTime.equals("最近半年")){
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 and a.post_time>DATE_SUB(CURDATE(), INTERVAL 6 MONTH)";
}else if(postTime.equals("最近一年")){
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 and a.post_time>DATE_SUB(CURDATE(), INTERVAL 1 YEAR)";
}else {
sql_fy=columnSql+"where a.user_id=b.user_id and a.post_state=1 ";					
}					
System.out.println(sql_fy);						
forumPostList = jdbcTemplate.queryForList(sql_fy); //將日誌集合儲存到List中
if(forumPostList.size()==0||flag==false) {
	return ERROR;
}	
					
return SUCCESS;	
				
				
} catch (Exception e) {				
	e.printStackTrace();
	return ERROR;
}
			
			
}