准备语句SQL语法出错

时间:2014-04-14 20:04:25

标签: sql java-ee prepared-statement

上面的queria适用于MySqlWorkBench

select t1.id, t1.col1, t1.col2, t1.col3, t1.col4 from test_table t1,
(select count(col2) n, col2 from test_table group by col2) t2
where t2.n > 1 AND t1.col2 = t2.col2;`

但是当我在我的Java方法中使用..与PreparedStatement stmt我得到错误 “您的SQL语法有错误;请查看与您的MySQL服务器对应的手册”

这是我的方法:

public ArrayList<Tuple> getRepeatedTuples(String columns) {

    ArrayList<Tuple> tuples = new ArrayList<Tuple>();

    String sql = "select t1.id, t1.col1, t1.col2, t1.col3, t1.col4"
            + "from test_table t1, (select count(?) n, ? from test_table group by ? ) t2 where t2.n > 1 AND t1.? = t2.?";

    try {
        // prepared statement para inserção
        PreparedStatement stmt = connection.prepareStatement(sql);
        stmt.setString(1, columns);
        stmt.setString(2, columns);
        stmt.setString(3, columns);
        stmt.setString(4, columns);
        stmt.setString(5, columns);
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {

            // criando o objeto Tuple

            Tuple tuple = new Tuple();
            tuple.setId(rs.getLong("id"));
            tuple.setValue1(rs.getString("col1"));
            tuple.setValue2(rs.getString("col2"));
            tuple.setValue3(rs.getString("col3"));
            tuple.setValue4(rs.getLong("col4"));

            tuples.add(tuple);
        }

        rs.close();
        stmt.close();
        return tuples;

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        throw new RuntimeException(e);
    }

}

}

需要帮助构建preparedStatement。 谢谢

0 个答案:

没有答案