/**
*
*/
package com.wtt.page.impl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.wtt.page.dao.PersonDAO;
import com.wtt.page.dbc.DataBaseConnection;
import com.wtt.page.vo.Person;
/**
* @author 王田甜 tim_wang
*
*/
public class PersonDAOImpl implements PersonDAO {
private DataBaseConnection dbc = null;
// 在构造方法里实现数据的连接
public PersonDAOImpl() {
this.dbc = new DataBaseConnection();
}
// 获取数据库总记录数
public int getAllCount() throws Exception {
int count = 0;
String sql = "SELECT COUNT(id) from person";
PreparedStatement pstmt = null;
try {
pstmt = this.dbc.getConnection().prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
pstmt.close();
rs.close();
} catch (Exception e) {
throw e;
}
return count;
}
// 根据传过来的参数进行模糊查询
public int getByLikeCount(String cond) throws Exception {
int count = 0;
String sql = "SELECT COUNT(id) from person WHERE uid LIKE ? OR name LIKE ?";
PreparedStatement pstmt = null;
try {
pstmt = this.dbc.getConnection().prepareStatement(sql);
pstmt.setString(1, "%" + cond + "%");
pstmt.setString(2, "%" + cond + "%");
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
pstmt.close();
rs.close();
} catch (Exception e) {
throw e;
}
return count;
}
// 根据传过来的当前页数和每页大小数进行查询全部
public List queryAll(int currentPage, int lineSize) throws Exception {
// 使用了泛型
List<Person> all = new ArrayList<Person>();
// 从数据里只查询符合指定大小的全部的记录
String sql = "SELECT id,uid,name,password FROM person limit "
+ (currentPage - 1) * lineSize + "," + lineSize;
PreparedStatement pstmt = null;
try {
pstmt = this.dbc.getConnection().prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Person p = new Person();
p.setId(rs.getInt(1));
p.setUid(rs.getString(2));
p.setName(rs.getString(3));
p.setPassword(rs.getString(4));
// 用list保存所有记录
all.add(p);
}
rs.close();
pstmt.close();
} catch (Exception e) {
throw e;
} finally {
this.dbc.close();
}
return all;
}
// 根据传过来的参数,当前页数和每页大小数进行查询符合条件的数据
public List queryByLike(String cond, int currentPage, int lineSize)
throws Exception {
List<Person> all = new ArrayList<Person>();
// 从数据里只查询符合条件的记录,带where 查询
String sql = "SELECT id,uid,name,password FROM person WHERE uid LIKE ? OR name LIKE ? limit "
+ (currentPage - 1) * lineSize + "," + lineSize;
PreparedStatement pstmt = null;
try {
pstmt = this.dbc.getConnection().prepareStatement(sql);
pstmt.setString(1, "%" + cond + "%");
pstmt.setString(2, "%" + cond + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Person p = new Person();
p.setId(rs.getInt(1));
p.setUid(rs.getString(2));
p.setName(rs.getString(3));
p.setPassword(rs.getString(4));
all.add(p);
}
rs.close();
pstmt.close();
} catch (Exception e) {
throw e;
} finally {
this.dbc.close();
}
return all;
}
};
评论0
最新资源