首页 > 解决方案 > SQL select 命令只返回列名

问题描述

在 MySQL 上的 Java JDBC 中使用 select 查询时,它似乎只返回列的名称,而不是与它们关联的值。例如,Content即使这是列的名称而不是它的值,以下方法也会返回。

public <T> T select(String column, @Nullable List<DBCondition> conditions) {
    try (Statement statement = MySQL.createStatement()) {
        ResultSet rs = statement.executeQuery("select '" + column + "' from " + name + (conditions == null || conditions.isEmpty() ? "" : " " + MySQL.conditionsListToString(conditions)) + ";");
        rs.next();
        return (T) rs.getObject(column);
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

在调试创建的查询时,最终select Content from testtable where Name='Main_test';返回的是 Content 而不是{"Test":"Workss"}预期的。这是意料之中的,因为在 MySQL“调试器”中运行完全相同的查询会返回

+-------------------+
| Content           |
+-------------------+
| {"Test":"Workss"} |
+-------------------+
1 row in set (0.00 sec)

我做错了什么,我该如何解决?

标签: javamysqlsql

解决方案


不要使用'。利用" + column + "


推荐阅读