准备语句执行查询错误(com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException)

时间:2017-07-25 13:20:32

标签: java mysql hikaricp

我编写了一个简单的方法来从数据库中获取字符串:

    public String getUserString(int id, String table, String column) {
    String output = null;
    try {
        String sql = "SELECT ? FROM ? WHERE id=?;";
        PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
        preparedStatement.setString(1, column);
        preparedStatement.setString(2, table);
        preparedStatement.setInt(3, id);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            output = resultSet.getString(column);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return output;
}

但是当我尝试使用它时:coreMySQL.getUserString(1, "economy", "balance");

我收到此错误: https://pastebin.com/BMAmN4Xh

2 个答案:

答案 0 :(得分:0)

您无法使用setXxx PreparedStatement方法设置表名和列名。它只能用于设置值。

但是,您可以使用简单的String替换来替换表名和列名,例如:

String query = SELECT <column> FROM <table> WHERE id=?;
String sql = query.replaceAll("<column>", column).replaceAll("<table>", table);
PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
    output = resultSet.getString(column);
}

答案 1 :(得分:0)

将查询模板定义为:

String queryTemplate = "SELECT %s FROM %s where id = ?;";

// Inside Function:

PreparedStatement preparedStatement = getConnection().prepareStatement(String.format(template, column, table));
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();