如何在java中访问另一个类中的连接对象?

时间:2013-02-19 14:59:29

标签: java mysql jdbc

我正在使用xampp mysql,这段代码用于JDBC程序。实际上有两个类是dbconnect.java,另一个是login.java。我想访问另一个类(即login.java)中的连接对象(即conn)。但是我没有正确的想法,我在这里包含了代码,请告诉我问题是什么,解决方案是什么?

这是dbconnect.java的代码

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);
        }
    }
}

这是来自另一个名为login.java

的类的代码
if(source==login){
    if(username!=null && 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);
    }
}

真正的问题是什么以及如何解决?

2 个答案:

答案 0 :(得分:6)

最简单的方法是使连接方法非void并返回连接:

public Connection 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");
        }
        return con;
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

答案 1 :(得分:0)

您应该从连接类返回CONNECTION对象并将其分配给您的登录类...现在您的连接对象为空...