java如何从主方法中获取要通过getConnection方法访问的值?
我试图获取main方法将产生的值,并在getConnection方法中使用它们。但是,当我尝试访问getConnection方法时,返回的是null值
我想使用ConnectionManager类连接到数据库
代码如下
public class ConnectionManager {
public static String database;
public static String dbuser;
public static String dbpassword;
public static void main(String args[]) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
database = prop.getProperty("database");
dbuser = prop.getProperty("dbuser");
dbpassword = prop.getProperty("dbpassword");
System.out.println(database);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String url = "jdbc:mysql://localhost:3306/" + database;
private static String driverName = "com.mysql.jdbc.Driver";
private static String username = dbuser;
private static String password = dbpassword;
private static Connection con;
public static Connection getConnection() {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. For example:
System.out.println("Failed to create the database connection.");
System.out.println(url + " " + username + " " + password);
}
} catch (ClassNotFoundException ex) {
System.out.println("Your driver has not been found.");
}
return con;
}
}
# 1 楼答案
静态c字段在类加载时初始化一次。当连接字段仍然为空时,将其设置为ConnectionManager字段一次
要“修复”您的问题,请让连接中的代码使用ConnectionManager中的字段:
# 2 楼答案
您在
DriverManager.getConnection(url, username, password)
调用中得到空参数值,因为您已将它们声明为静态字段因此,在从
config.properties
读取特定值之前,将它们初始化为nulls
让我们跟随流程:
静态初始化步骤:
方法主执行:
方法getConnection执行:
注:如前所述,最好使用带有如下参数的函数:
# 3 楼答案
只需使用参数调用getConnection()方法
然后,调用这个方法