按preparementment语句执行的命令不排序

时间:2018-11-11 14:58:35

标签: java

我尝试通过preparestatement通过order by语句查询一个选择的sql,它被算了,但是在打印时,它没有排序。有人帮我吗?

Connection conn = ConnectionUtils.getConnect();
        String sql = "SELECT  * FROM student ORDER BY ?";
        List<Student> listStudent = new ArrayList<>();
        try {
            PreparedStatement prepareStatement = conn.prepareStatement(sql);
            prepareStatement.setString(1, name);
            ResultSet rs = prepareStatement.executeQuery();
            while (rs.next()) {
                Student student = new Student();
                student.setId();
                ......vv
                listStudent.add(student);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listStudent;

1 个答案:

答案 0 :(得分:0)

在准备好的语句中,您可以使用?参数或占位符来传递实际值,而不是列名,例如WHERE子句:WHERE column1 = ?中。

因此更改为:

String sql = "SELECT  * FROM student ORDER BY " + name;

并删除此行:

prepareStatement.setString(1, name);