其他分享
首页 > 其他分享> > PreparedStatement问号的问题

PreparedStatement问号的问题

作者:互联网

Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "select ?, ?, ? from dept";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "deptno");
            ps.setString(2, "dname");
            ps.setString(3, "loc");
            rs = ps.executeQuery();
            ArrayList<Dept> depts = new ArrayList<>();
            while (rs.next()) {
                String deptno = rs.getString("deptno");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                System.out.printf("%s %s %s\n", deptno, dname, loc);
                final Dept dept = new Dept(deptno, dname, loc);
                depts.add(dept);
            }
            request.setAttribute("depts", depts);
            request.getRequestDispatcher("/list.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

结果

deptno dname loc
deptno dname loc
deptno dname loc
deptno dname loc
deptno dname loc
deptno dname loc
deptno dname loc
deptno dname loc

总结

PreparedStatement只能用来为可以加引号’的参数(如参数值)设置动态参数,即用?占位,不可用于表名、字段名等。

标签:loc,PreparedStatement,String,ps,dname,rs,问题,deptno,问号
来源: https://www.cnblogs.com/Shinki/p/16477372.html