DB oracle Closed Connection

Asked

Viewed 81 times

3

Introducing

I am developing an application and have to add data to an oracle database that is local. Using JDBC I connect

 try (Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@" + conexao + ":1521:xe", "system", "root")){
            System.out.println("Conectado a "+conexao);
            return (Connection) conn;
        }

Connection is made successfully. Now I need to insert. I have the following code:

Personal.java.

public void insert(String conexao) throws SQLException{
        // Instancia classe de conexão 
        Connection conn = ConnDb.getConnection(conexao);
        String query = "insert into TESTE2 (TITLE) values('asd')";
        try (PreparedStatement stmt = conn.prepareStatement(query)) {
           stmt.execute();
           conn.commit();
        }catch(SQLException e){
           System.out.println(e.getMessage());
        }            
    }

And what is triggered when clicked on a button

String conexao= localConexao.getText();
         try {
            p = new PessoaDAO();
            p.insert(conexao);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }

Error

He falls into a SQLException not making the insertion.

Closed Connection

1 answer

5


You are closing the connection right after opening it:

try (Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@" + conexao + ":1521:xe", "system", "root")){
            System.out.println("Conectado a "+conexao);
            return (Connection) conn;

// a linha abaixo libera os recursos alocados quando da criação de "conn"; ou seja, fecha a conexão com o banco.
        } 

To test the rest of your code, remove the try of creating the connection:

Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@" + conexao + ":1521:xe", "system", "root");
System.out.println("Conectado a "+conexao);
return (Connection) conn;

Of course now your connection will remain open and eventually you will need to create another way to manage it.

Behold: Java Tutorials - The Try-with-Resources Statement.

  • @That’s what Caffe was! Thank you =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.