PreparedStatement接口的补充问题——占位符

来源:互联网 发布:latex软件 编辑:程序博客网 时间:2024/05/29 16:51

PreparedStatement接口继承于Statement接口,所以它拥有Statement接口中的方法,详情见
在实际开发中我们在编写SQL语句的时候可能会用到占位符?,它可以代替SQL语句的参数,然后通过setXXX()方法对SQL语句的参数进行赋值。例如

public List<Employee> selectEmp(int firstResult, int pageSize) {        Connection con = null;        List<Employee> list = new ArrayList<Employee>();        try {            con = DBCon.getCon();            String sql = "select  * from tb_employee order by id limit ?,?";            PreparedStatement pstmt = con.prepareStatement(sql);            pstmt.setInt(1, firstResult);//调用PreparedStatement接口中的setInt方法            pstmt.setInt(2, pageSize);            ResultSet rs = pstmt.executeQuery();            while (rs.next()) {                Employee emp = new Employee();                emp.setEmpId(rs.getInt("id"));                emp.setEmpName(rs.getString("name"));                emp.setEmpSex(rs.getString("sex"));                emp.setEmpAge(rs.getInt("age"));                emp.setTelephoneNo(rs.getString("telephoneNo"));                emp.setAddress(rs.getString("address"));                list.add(emp);            }            rs.close();        } catch (Exception ex) {            ex.printStackTrace();        } finally {            try {                con.close();            } catch (SQLException e) {                e.printStackTrace();            }        }        return list;    }
0 0
原创粉丝点击