package com.njtysoft.page.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.njtysoft.page.dto.User;
public class UserDAO {
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private Connection getConn() { //此连接mysql数据库
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "pass");
}catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
private String getSql(String name) { //整理SQL语句
String[] strr = name.trim().split(" ");
String sql = "select * from help_keyword where name like \'%" + strr[0] + "%\'";
for(int i = 1; i < strr.length; i++) {
if(strr[i].equals("")) {
continue;
}
sql = (new StringBuilder()).append(sql).append(" or name like \'%" + strr[i] + "%\'").toString();
}
return sql;
}
//获得需要向前台显示的数据集
public List<User> getUsersByLikeName(String name, int currentPage, int pageSize) {
List<User> users = new ArrayList<User>();
String sql = this.getSql(name);
int rowStart = (currentPage - 1) * pageSize;
sql = sql + " limit " + rowStart + ", " + pageSize; //每次只获得一页的数据
try {
conn = this.getConn();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
int id = rs.getInt("help_keyword_id");
String mname = rs.getString("name");
User user = new User(id, mname);
users.add(user);
}
return users;
}catch(Exception ex) {
ex.printStackTrace();
}finally {
this.close();
}
return null;
}
//获得符合查询条件的总记录数
public int getAllRows(String name) {
int allRows = 0;
String sql = this.getSql(name);
try {
conn = this.getConn();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
allRows ++;
}
return allRows;
}catch(Exception ex) {
ex.printStackTrace();
}finally {
this.close();
}
return 0;
}
private void close() {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
- 1
- 2
前往页