How to access a Connection type variable from another claSe?

1

you can have a class from:

Conection cn;    
cn=DriverManager.getConnection("jdbc:mysql://localhot:3306/BD","root","pass");

// and from another class, which is the one that inserts a record, call the connection variable "cn"? The idea is to have the connection class separated from the class that makes the insert.

PreparedStatement ST;

ST=cn.preparedStatement("");

// I get an error that does not find "cn" as variable q contains the connection, try also importing the claSe but in success.

    
asked by Augusto Acha 15.06.2018 в 04:11
source

2 answers

0

We could do it this way.

  • Initialize the connection in your constructor.
  • Have a method to get the connection from another class.
  • And also another method to make the disconnection ..
public class BaseDatosPG {
    private Connection conn = null;

    public BaseDatosPG(){
        String urlDatabase = "jdbc:mysql://localhost:3306/BD";
        String user = "root", pass = "pass";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(urlDatabase, user, pass);

        } catch (SQLException ex){
            System.out.println("Excepción: "+ ex.getMessage());
        } catch (ClassNotFoundException ex){
            System.out.println("Excepción no encontró driver: "+ ex.getMessage());
        }
    }

    public Connection getConnection(){
        return this.conn;
    }

    public void desconectarBD(){
        System.out.println("Cerrar conexión a base de datos");
        if(conn != null){
            try {
                conn.close();

            } catch (SQLException ex) {
                System.out.println("No se realizó la desconexión: " + ex.getMessage());
            }
        }
    }

}

And when it comes to recovering that connection ..

BaseDatosPG bd = new BaseDatosPG();
PreparedStatement pST = bd.getConnection().preparedStatement("");
    
answered by 15.06.2018 / 05:51
source
0

Use the static reserved word:

 public static Conection cn=DriverManager.getConnection("jdbc:mysql://localhot:3306/BD","root","pass");

and you will access from any other class with:

ClaseDondeDeclareCn.cn...
    
answered by 15.06.2018 в 04:40