2
respostas

Onde se encontra o erro ?

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class AdicionarProduto {

    public static void main(String[] args) throws SQLException {

        Scanner scan = new Scanner(System.in);
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.recuperarConexao();

        String nome = scan.next();
        String descricao = scan.next();

        PreparedStatement stm = connection.prepareStatement("INSERT INTO PRODUTO (nome, descricao) VALUES (?, ?)",
                PreparedStatement.RETURN_GENERATED_KEYS);
        stm.setString(1, nome);
        stm.setString(2, descricao);
        ResultSet rst = stm.getGeneratedKeys();

        stm.execute();

        while (rst.next()) {
            String produto = rst.getString(nome);
            System.out.println(produto + " adicionado");

        }

        scan.close();

    }

}
2 respostas

Erro retornado:

Exception in thread "main" java.sql.SQLException: Operation not allowed after ResultSet closed at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) at com.mysql.cj.jdbc.result.ResultSetImpl.checkClosed(ResultSetImpl.java:437) at com.mysql.cj.jdbc.result.ResultSetImpl.next(ResultSetImpl.java:1712) at AdicionarProduto.main(AdicionarProduto.java:26)

Tenta fazer o stm.execute() antes de instanciar o ResultSet.

stm.execute();

try (ResultSet rst = stm.getGeneratedKeys()) {
    while (rst.next()) {
        // ...
    }
}