commons-dbutil 谁借莪1个温暖的怀抱¢ 2024-04-18 21:14 96阅读 0赞 /\*\* 员工实体类 \*/ public class Employee { private int id; private String name; private int age; private String position; public Employee() { } public Employee(int age, String name, String position) { super(); this.age = age; this.name = name; this.position = position; } //以下省略所有属性的getter和setter …… @Override public String toString() { return "[id=" + this.id + ",name=" + this.name + ",age=" + age + ",position=" + this.position + "]"; } \} import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.qiujy.common.MyDbUtils; import org.qiujy.domain.Employee; /\*\* 员工dao \*/ public class EmployeeDao { //新增一个员工信息 public void insertEmployee(Connection conn, Employee empl) throws DAOException { String sql = "INSERT INTO employee(name,age,position) valus (?,?,?)"; try { QueryRunner qr = new QueryRunner(); Object[] params = {empl.getName(), empl.getAge(),empl.getPosition()}; qr.update(conn, sql, params); } catch (SQLException e) { throw new DAOException(e); } } public void deleteEmloyeeById(Connection conn, int id) throws DAOException { String sql = "DELETE FROM employee WHERE id=?"; try { QueryRunner qr = new QueryRunner(); qr.update(conn, sql, id); } catch (SQLException e) { throw new DAOException(e); } } public void updateEmployee(Connection conn, Employee empl) throws DAOException { String sql = "UPDATE employee SET name=?,age=?,position=? WHERE id=?"; try { QueryRunner qr = new QueryRunner(); Object[] params = { empl.getName(), empl.getAge(), empl.getPosition(), empl.getId() }; qr.update(conn, sql, params); } catch (SQLException e) { throw new DAOException(e); } } public Employee getEmployeeById(Connection conn, int id) throws DAOException { Employee empl = null; String sql = "SELECT id,name,age,position FROM employee WHERE id=?"; try { QueryRunner qr = new QueryRunner(); empl = (Employee) qr.query(conn, sql, id, new BeanHandler(Employee.class)); } catch (SQLException e) { throw new DAOException(e); } return empl; } /** * 获取所有的员工列表 * @param conn * @return 员工实例列表 * @throws DAOException */ @SuppressWarnings("unchecked") public List<Employee> getEmployeeList(Connection conn) throws DAOException { List<Employee> list = null; String sql = "SELECT id,name,age,position FROM employee"; try { QueryRunner qr = new QueryRunner(); list = (List<Employee>) qr.query(conn, sql, new BeanListHandler(Employee.class)); } catch (SQLException e) { throw new DAOException(e); } return list; } public static void main(String[] args) throws SQLException { Connection conn = MyDbUtils.getConnection(); List<Employee> list = new EmployeeDao().getEmployeeList(conn); for(Employee empl : list){ System.out.println(empl); } DbUtils.close(conn); }
还没有评论,来说两句吧...