package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import classes.Emp;
public class EmpDao {
private static final String sql="select * from emp limit ?,?";
private static final String sql2="select count(*) from emp";
private static final String sql3="insert into emp values(?,?,?)";
private static final String sql4="delete from emp where id=?";
private static final String sql5="update emp set name=?,salary=? where id=?";
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
public List<Emp> getEmpList(int page,int rowsPerPage){
List<Emp> list=null;
try {
con=ConnectionUtil.getConnection();
ps=con.prepareStatement(sql);
ps.setInt(1,rowsPerPage*(page-1));
ps.setInt(2,rowsPerPage);
rs=ps.executeQuery();
list = new ArrayList();
while(rs.next()){
Emp emp=new Emp(rs.getInt(1),rs.getString(2),rs.getDouble(3));
list.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
ConnectionUtil.release(con, ps, rs);
}
return list;
}
public int getTotalPage(int rowsPerPage) {
int totalPage=0;
try {
con=ConnectionUtil.getConnection();
ps=con.prepareStatement(sql2);
rs=ps.executeQuery();
if(rs.next()){
totalPage=rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
ConnectionUtil.release(con, ps, rs);
}
if(totalPage%rowsPerPage!=0){
return totalPage/rowsPerPage+1;
}
return totalPage/rowsPerPage;
}
public void addEmp(int id,String name,double salary){
try {
con=ConnectionUtil.getConnection();
ps=con.prepareStatement(sql3);
ps.setInt(1,id);
ps.setString(2,name);
ps.setDouble(3,salary);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
ConnectionUtil.release(con, ps, rs);
}
}
public void delEmp(int id){
try {
con=ConnectionUtil.getConnection();
ps=con.prepareStatement(sql4);
ps.setInt(1,id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
ConnectionUtil.release(con, ps, rs);
}
}
public void updateEmp(int id,String name,double salary){
try {
con=ConnectionUtil.getConnection();
ps=con.prepareStatement(sql5);
ps.setString(1,name);
ps.setDouble(2,salary);
ps.setInt(3,id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
ConnectionUtil.release(con, ps, rs);
}
}
}
评论4
最新资源