DB oracle Closed Connection

3

Introduction

I'm developing an application and I have to add data to an oracle database that is local. Using JDBC I make the connection

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

Connection is successful. Now I need to do the insertion. I have the following code:

PersonaDAO.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's triggered when you click a button

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

Error

It falls into a SQLException not doing the insertion.

  

Closed Connection

    
asked by anonymous 16.09.2014 / 23:08

1 answer

5

You are closing the connection shortly after you open 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 from the connection creation:

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

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

See: Java Tutorials - The try-with-resources Statement .

    
17.09.2014 / 00:02