java - 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!
解决方案
该变量myConn
遮蔽了静态变量myConn
。所以你正在做的是 - 你正在初始化一个名为的局部变量myConn
而不是类变量。
只需删除(重新)在main
.
try {
//Initializes the static variable myConn
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xyz);
}
推荐阅读
- java - 如何为带有堆栈的迭代器类设置构造函数?
- javascript - 如何使用Javascript访问特定行的excel文件
- pyspark - 如何在pyspark中自动删除常量列?
- php - docker compose 环境变量未在 Dockerfile 中设置变量
- r - R:将特定元素从数据框更改为列名并将行切换为列
- excel - 试图将字符串拆分为新列
- matlab - 如何创建滚动窗口协方差矩阵并计算各自的权重?
- javascript - 为什么在构建脚本中使用“rimraf dist”命令
- jquery - 使用jQuery而不是CSS防止按钮单击时页面滚动
- vba - 通过 xmlhttp 传递授权