title: how to access connection object in another class in java?
body: <p>i am using xampp mysql, this code is for JDBC program. actually there are two class one is dbconnect.java and another is login.java. I want to access the connection object (i.e. conn) in another class(i.e. login.java). But i don't have proper idea, i have included the code here please suggest me what is the problem and what are the solutions?</p>
  
  <p>This is the code of dbconnect.java</p>
  
  <pre><code>package stundentrecord;
  
  import java.sql.Connection;
  import java.sql.DriverManager;
  
  public class dbconnect {
      public void conect(){
          Connection con = null;
          String url = "jdbc:mysql://localhost:3306/";
          String db = "studentRecord";
          String driver = "com.mysql.jdbc.Driver";
          String user = "root";
          String pass = "";
          try{
              Class.forName(driver);
              con = DriverManager.getConnection(url + db, user, pass);
              if(con==null){
                  System.out.println("Connection cannot be established");
              }
              // con.close();
          } catch (Exception e) {
              System.out.println(e);
          }
      }
  }
  </code></pre>
  
  <p>and here is the code from another class named login.java</p>
  
  <pre><code>if(source==login){
      if(username!=null &amp;&amp; password!=null) {
          Connection conn= null;
          Statement stmt = null;
          dbconnect db = new dbconnect();
          db.conect();
          String query = "SELECT * from userlogin";
          try{
              stmt=(Statement) conn.createStatement(); // here is the problem
              ResultSet rs = stmt.executeQuery(query);  // here is the problem 
              while (rs.next()) {
                  String user = rs.getString("username");
                  String pass=rs.getString("password");
                  System.out.println("Welcome "+user);
              }
          } catch(SQLException ex){
              ex.getMessage();
          }
          StundentRecord SR = new StundentRecord();
      } else {
          JOptionPane.showMessageDialog(null,"Username or password field is empty","error    !!",JOptionPane.ERROR_MESSAGE);
      }
  }
  </code></pre>
  
  <p>What is the real problem and how to solve it?</p>