Java – MySQL 连接 getter

Java – MySQL connection getter

我需要将我的连接发送到 CarDAO class。我为此创建了 getMyConn getter,但它键入我 "myConn cannot be resolved to a variable"。我如何为此创建 getter?

public class ConnectionDB {
    public ConnectionDB() {

        String dbHost="localhost";
        String dbDatabase="cars";
        String dbUser = "root";
        String dbPassword = "";
        String connectionUrl = "jdbc:mysql://" + dbHost
                + "/" + dbDatabase
                + "?user=" + dbUser
                + "&password=" + dbPassword;
        try{
        // 1. Get a connection do database
        Connection myConn = DriverManager.getConnection(connectionUrl);
        // 2. Create a statement
        Statement myStmt = myConn.createStatement();
        // 3. Execute SQL query
        String sql = "";
        //int rowsAffected = myStmt.executeUpdate(sql);
        //System.out.println("Rows affected " + rowsAffected);
        // 4. Process the result set
        }
        catch(Exception exc) {
            exc.printStackTrace();
        }
    }
    public Connection getMyConn(){
        return myConn;
    }
}

只需将 myConn 放在构造函数之外,使其成为对象的属性。

 Connection myConn;

然后,在构造函数中,

try{
    // 1. Get a connection do database
    myConn = DriverManager.getConnection(connectionUrl);
    // 2. Create a statement
    Statement myStmt = myConn.createStatement();
    // 3. Execute SQL query
    String sql = "";
    //int rowsAffected = myStmt.executeUpdate(sql);
    //System.out.println("Rows affected " + rowsAffected);
    // 4. Process the result set
}

此外,不建议在构造函数中初始化连接。您可以使用单例 class 在需要时获取连接。