如何从getConnection方法访问主方法的值?
我想获取主要方法会产生的值,并在getConnection方法中使用它们。但是,当我尝试访问getConnection方法时,返回空值。如何从getConnection方法访问主方法的值?
我想使用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;
}
}
你只需要调用带有参数的getConnection()方法。
public static Connection getConnection(String url, String username, String password) {
/* Your code here */
}
然后,调用这个方法。
Connection connection = getConnection(url, username, password);
静态c字段在加载类时被初始化一次。连接字段设置为连接管理器字段一次,当它们仍然为空时。
“修理”你的问题,有你的连接代码使用的字段中的ConnectionManager:
con = DriverManager.getConnection(url, ConnectionManager.dbuser, ConnectionManager.dbpassword);
不起作用。仍然返回null。 –
你在DriverManager.getConnection(url, username, password)
越来越空参数值调用,因为你已经声明他们为静态字段。
所以你初始化它们为nulls
你读从config.properties
特定值之前,让我们跟随流量:
静态初始化步骤:
private static String username = dbuser; //username==null; dbuser==null;
private static String password = dbpassword; //password==null; dbpassword==null
private static Connection con; //con==null;
方法主要执行:
database = (prop.getProperty("database"));
dbuser = (prop.getProperty("dbuser")); //dbuser="smth"; username==null
dbpassword = (prop.getProperty("dbpassword")); //dbpassword ="smth"; password==null
getConnection方法执行:
con = DriverManager.getConnection(url, username, password); //username==null; //password==null;
PS:正如先前所说,这是最好使用带有参数的函数是这样的:
public static Connection getConnection(String url, String username, String password) {
/* Your code here */
}
谢谢。它进行了一些修改。 –
参数的值将来自公共静态无效的主要(字符串参数[]) –
谢谢。它进行了一些修改。 –