为什么会出现此错误:E / ERROR:executeQuery方法必须返回结果集。

时间:2019-05-10 13:45:48

标签: java android sql-server-2008 compiler-errors

我正在尝试将我的项目与SQL-Server数据库连接。但是我总是收到此错误E / ERROR:executeQuery方法必须返回结果集。

Class.forName("net.sourceforge.jtds.jdbc.Driver");
        String username = "un";
        String password = "pass";

        conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);

        Log.w("Connection","open");

        String sql = "INSERT INTO TABLE" +
                "(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
                "VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
        Statement stmt = conn.createStatement();
        ResultSet rSet = stmt.executeQuery(sql); // error here

我尝试将stmt.executeQuery更改为stmt.executeUpdate,但用红色下划线标出,并指出输出为int,因此不兼容。

2 个答案:

答案 0 :(得分:1)

使用PreparedStatement更安全。

Class.forName("net.sourceforge.jtds.jdbc.Driver");
    String username = "un";
    String password = "pass";

    conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);

    Log.w("Connection","open");

    String sql = "INSERT INTO TABLE" +
            "(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
            "VALUES (?, ?, ?, ?, ?)";

    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
        pstmt.setString(1, informacao.getNomeCliente())
        pstmt.setString(2, informacao.getNome())
        pstmt.setString(3, informacao.getEmail())
        pstmt.setString(4, informacao.getSatisfacao())
        pstmt.setString(5, informacao.getNota())

        int result = pstmt.executeUpdate();

    } catch (SQLException e) {
                e.printStackTrace();
    }

答案 1 :(得分:0)

我认为您在查询数据库中的表时(当您使用executeQuery关键字时)应该使用SELECT方法。当您想执行SQL语句(例如INSERTUPDATE等)时,应使用execute方法,如here所示。

您可以尝试以下方法:

Boolean rSet = stmt.execute(sql);