2015-12-15 21 views
0

我使用這個類連接到postgres數據庫,我如何在Jframe或其他類中使用此連接?在另一個類或Jframe中使用連接方法

public class ConexionDB { 
     private Connection conexion; 

     public Connection conectar() { 
      boolean estaConectado = false; 
      String url = "jdbc:postgresql://localhost:5432/evaluacion"; 
      String password = "postgres"; 

      try { 
       Class.forName("org.postgresql.Driver"); 
       this.conexion = DriverManager.getConnection(url, "postgres", password); 
       estaConectado = true; 
       System.out.println("Conectando a Base de Datos ..."); 
      } catch (Exception ex) { 
       System.out.println("Problemas de Conexion"); 
       estaConectado = false; 
      } 
      return conexion; 
     } 
    } 

回答

0
Connection connection = new ConexionDB().conectar(); 

您可以使用如上創建Connection並使用它..

+0

謝謝對於答案,我做了你所說的,它拋出一個錯誤,說該方法不存在於類ConexionDB中,但它在那裏,netbeans建議我在ConexionDB中創建一個方法,所以我做了,然後抹去了相同的方法,並且突然發現你給出的行沒有再顯示錯誤....它是一個錯誤? –

+0

1)爲了更好地提供幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 2)總是複製/粘貼錯誤和異常輸出! –

+0

我應該如何複製粘貼代碼行下的紅線和一個帶有紅點的燈泡! –

0

可以調用方法和無論你想 例如創建一個新的連接

class A{ 
    publlic static void main(String args[]){ 
     ConexionDB conexionDB = new ConexionDB(); 
     try(Connection conn = conexionDB.conectar()){ 
      // use the connectionr here 
     } catch (SQLException e){ 
      //exception handling 
     } 
    } 
} 
相關問題