首页 > 解决方案 > How to make use of a try{}-block-variable in a method?

问题描述

I would like to pass the connection-variable myConn to several other classes. However, when I

return myConn;

myConn cannot be resolved to a variable. Here is the code:

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

I have to tried to fix the problem by making the method static and adding a static variable:

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

Now, the program runs, but the static variable remains null, thus remains untouched by

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

The same problems occur when omitting the try-block and working with

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

How can I fix this? Help would be much appreciated!

标签: javajdbctry-catch

解决方案


该变量myConn遮蔽了静态变量myConn。所以你正在做的是 - 你正在初始化一个名为的局部变量myConn而不是类变量。

只需删除(重新)在main.

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

推荐阅读