By PlanetTeamSpeak


2018-08-10 12:02:35 8 Comments

When using the select query in Java JDBC on MySQL, it seems to only return the column's names and not the values associated with them. Like for instance, the following method returns Content even though that's the name of the column and not the value of it.

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;
    }
}

While debugging the created query ended up being select Content from testtable where Name='Main_test'; which returns Content and not {"Test":"Workss"} as expected. This is expected because running the exact same query in the MySQL 'debugger' returns

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

What am I doing wrong and how can I fix this?

2 comments

@PlanetTeamSpeak 2018-08-10 12:40:38

Thanks to Alex K. for posting the correct answer, I had already figured my problem was quite had quite an obvious fix which it did. The fix was to not put the column in quotes, but rather in graves, so instead of doing "select '" + column + "' from " I should instead have done "select" + column + "from " but not putting the column in anything will also work.

@Nico Zimmer 2018-08-10 12:37:05

Dont use '. Use " + column + "

@PlanetTeamSpeak 2018-08-10 12:38:56

Well that worked, but I am gonna go with what Alex K. said with the graves since that seems safer and a better practice.

Related Questions

Sponsored Content

29 Answered Questions

[SOLVED] How do I UPDATE from a SELECT in SQL Server?

39 Answered Questions

[SOLVED] How to import an SQL file using the command line in MySQL?

23 Answered Questions

[SOLVED] How do I perform an IF...THEN in an SQL SELECT?

38 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

37 Answered Questions

29 Answered Questions

[SOLVED] Find all tables containing column with specified name - MS SQL Server

29 Answered Questions

[SOLVED] SQL select only rows with max value on a column

8 Answered Questions

[SOLVED] 'IF' in 'SELECT' statement - choose output value based on column values

  • 2011-05-10 13:53:31
  • Michael
  • 1218213 View
  • 602 Score
  • 8 Answer
  • Tags:   mysql sql database

17 Answered Questions

4 Answered Questions

[SOLVED] MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

  • 2009-06-16 12:24:00
  • Chris Burgess
  • 159001 View
  • 27 Score
  • 4 Answer
  • Tags:   sql mysql

Sponsored Content