提供参数时,查询不起作用

时间:2015-10-19 22:51:58

标签: java mysql database

这个工作得很好

conn = DatabaseConnection.getConnection();
stmt = conn.prepareStatement("SELECT * FROM Persons ORDER by firstName Desc");
rs = stmt.executeQuery();

但是这个不起作用

conn = DatabaseConnection.getConnection();
stmt = conn.prepareStatement("SELECT * FROM Persons ORDER by ? ?");
stmt.setString(1, "firstName");
stmt.setString(2, "Desc");
rs = stmt.executeQuery();

不确定为什么这不起作用。我的参数都是变量,这就是我想要明确设置它的原因。

2 个答案:

答案 0 :(得分:0)

预备语句中的占位符(?)用于列替换。您无法使用ORDER BY方法设置setString的“DESC”属性。

来自PreparedStatement setString javadocs

 * Sets the designated parameter to the given Java <code>String</code> value.
 * The driver converts this
 * to an SQL <code>VARCHAR</code> or <code>LONGVARCHAR</code> value
 * (depending on the argument's
 * size relative to the driver's limits on <code>VARCHAR</code> values)
 * when it sends it to the database.

如果您想将ORDER作为DAO方法的参数,那么只需在查询中使用String替换。也许是这样的:

public myDAOMethod(String firstName, String order) {

    String query = "SELECT * FROM Persons ORDER by ? " + order;
    conn = DatabaseConnection.getConnection(query);
    stmt = conn.prepareStatement();
    stmt.setString(1, "firstName");
    rs = stmt.executeQuery();

}

答案 1 :(得分:0)

实际上,您的查询转换为类似于预准备语句的内容:

SELECT * FROM Persons ORDER by 'firstname' 'Desc'

此行为可防止SQL注入。