代码之家  ›  专栏  ›  技术社区  ›  Clyde Frog

如何在方法中使用try{}-块变量?

  •  0
  • Clyde Frog  · 技术社区  · 6 年前

    我想把连接变量myConn传递给其他几个类。但是,当我

    return myConn;
    

    myConn无法解析为变量。代码如下:

    import java.sql.*;
    import javafx.application.Application;
    
    public class MP {
    
        public static void main(String[] args) {
    
            try {
    
                Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xyz);
    
            }
            catch (Exception exc) {
                exc.printStackTrace();
            }
    
            Application.launch(MPfxlogin.class, args);      
        }
    
        public Connection getConn() {
    
            return myConn;  
        }   
    }
    

    我必须尝试通过使方法成为静态并添加静态变量来解决问题:

    import java.sql.*;
    import javafx.application.Application;
    
    public class MP {
    
        static Connection myConn;
    
        public static void main(String[] args) {
    
            try {
    
                Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xyz);
    
            }
            catch (Exception exc) {
                exc.printStackTrace();
            }
    
            Application.launch(MPfxlogin.class, args);      
        }
    
        public static Connection getConn() {
    
            return myConn;  
        }   
    }
    

    现在,程序运行了,但是静态变量仍然为空,因此不会被

    Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xyz);
    

    当省略try块并使用

    public static void main(String[] args) throws SQLException {
    

    我该怎么解决?非常感谢您的帮助!

    1 回复  |  直到 6 年前
        1
  •  4
  •   Thiyagu    6 年前

    变量 myConn 隐藏静态变量 麦肯 . 所以您要做的是-初始化一个名为 麦肯 而不是类变量。

    只需删除(重新)声明它的部分 main .

    try {
        //Initializes the static variable myConn
        myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xyz);
    }