在MySQL中执行SELECT命令时Statement.executeQuery()抛出java.sql.SQLSyntaxErrorException

时间:2019-01-18 11:40:18

标签: java mysql select jdbc sqlexception

我有一个使用JDBC API从MySQL数据库表中获取记录的方法。 我一直在使用的命令是:

"SELECT column_1, column_2, ... FROM table;"

列名以ArrayList的形式提供给方法,正在使用StringBuilder基于列名和表名构造查询。

使用createStatement()执行构造的查询时,它抛出:"java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near from $tableName' at line 1"

这是该方法的完整代码:

public ObservableList<ObservableList<String>> getTableData(String tableName, List<String> selectedParams, int rowCount) {
        try {
            StringBuilder query = new StringBuilder("select ");
            for (int i = 0; i < selectedParams.size(); i++) {
                query.append(selectedParams.get(i)).append(", ");
            }
            query.append("\b\b from ").append(tableName).append(" limit ").append(rowCount);
            System.out.println("query:" + query);
            ObservableList<ObservableList<String>> rows;
            try (ResultSet rset = st.executeQuery(query.toString())) {
                ResultSetMetaData rsmd = rset.getMetaData();
                rows = FXCollections.observableArrayList();
                while (rset.next()) {
                    ObservableList<String> row = FXCollections.observableArrayList();
                    int count = 1;
                    while (count <= rsmd.getColumnCount()) {
                        row.add(rset.getString(count));
                        count++;
                    }
                    rows.add(row);
                }
            }
            rows.forEach((row) -> {
                System.out.println(row);
            });
            return rows;
        } catch (SQLException ex) {
            Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

运行代码时,生成的查询表单打印语句如下所示:

"query:select territory from offices"

我已经直接针对db和另一个简单的JDBC程序测试了此查询,它们都运行良好。除此方法外。请帮忙。

---------------编辑:忘记粘贴异常消息:---------------

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near from offices limit 10' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1218)

2 个答案:

答案 0 :(得分:1)

问题ID

 for (int i = 0; i < selectedParams.size(); i++) {
                query.append(selectedParams.get(i)).append(", ");
            }

上面的代码将在参数名称后附加一个额外的',' 相反,您可以使用

query.append(String.join(", ", selectedParams))

答案 1 :(得分:1)

问题是

query.append("\b\b from ")

不会从StringBuilder中删除结尾的逗号和空格。它可能外观类似于将其打印到控制台时的样子,但是字符串实际上确实包含

select territory, ␈␈ from offices

MySQL显然不喜欢那样。

相反,您实际上想从StringBuilder中删除逗号(并留出空格):

query.deleteCharAt(query.length() - 2).append("from ")