2013-05-17 36 views
-2
private static Connection conexion() { 
    try { 

     //Cargamos el Driver MySQL 

     conexion = DriverManager.getConnection(server, user, pass); 


    } catch (Exception e) { 
     JOptionPane.showMessageDialog(null,"Error "+e); 
     System.out.println("SQLException: " + e.getMessage()); 
     System.out.println("SQLState: " + ((SQLException) e).getSQLState()); 
     System.out.println("VendorError: " + ((SQLException) e).getErrorCode()); 
    } 
    return conexion; 

} 

這就是我創建連接的地方。如何在不創建新連接的情況下從其他類調用該變量?我不想建立多個連接,我想爲我的整個Java程序使用相同的連接。如何從另一個類調用我的連接變量?

有沒有辦法調用該變量?我是一名新程序員。

+0

你不要從課堂上打電話。你可以從方法中調用事物。您的其他對象需要引用持有連接的對象。 – bmargulies

+0

我不是java的專家,但通常每個查詢後連接都會關閉。 –

+0

我強烈建議從一本關於Java的好手冊或Oracle提供的教程開始。 –

回答

0

你應該做這樣的事情

private Connection conn; 

public Connection getConn(){ 
    if(conn == null || conn.isClosed) 
     conn = DriverManager.getConnection(server, user, pass); 
    return conn; 
} 
在你要使用的連接類

...你總是需要關閉連接it'sa很好的做法,你的數據庫會感謝你

+0

所以我在類? – Adrian

+0

@Adrian你應該這樣做一個類'公共類Conexion {私有靜態連接conn;如果(conn == null || conn.isClosed) conn = DriverManager.getConnection(server,user,pass);如果(conn == null || conn.isclosed) conn = return conn;在類中你要使用連接'public class MyClass extends Conexion {Connection conn = getConn();' –

相關問題