我有一個使用屬性文件建立數據庫連接的java類。爲了將數據插入到表中,我編寫了另一個Java類,它從第一個類中獲取連接對象。嘗試將連接對象傳遞給另一個java類時出現NullPointerException
這裏是連接類調試時
package feedback;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DbConnection {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/online_feedback";
public static Connection con;
static String properties[] = new String[2];
public static Connection connectDB() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, properties[0], properties[1]);
System.out.println("Conn obj :::" + con);
System.out.println(properties[0]);
System.out.println(properties[1]);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public void loadProp() {
Properties prop = new Properties();
InputStream input = this.getClass().getResourceAsStream("connection.properties");
try {
prop.load(input);
} catch (IOException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("exception " + ex);
}
String username = prop.getProperty("username");
String password = prop.getProperty("password");
properties[0] = username;
properties[1] = password;
System.out.println(properties[0]);
System.out.println(properties[1]);
}
public static void main(String[] args) {
DbConnection d = new DbConnection();
d.loadProp();
Connection cont = d.connectDB();
System.out.println("okay " + cont);
}
}
此類工作正常。它打印用戶名,密碼以及連接對象。
這裏是第二類
package feedback;
import java.sql.Connection;
public class Test {
public static void main (String[] args){
Connection c = DbConnection.connectDB();
System.out.println("connected " + c);
}
}
問題是它打印null作爲連接對象。
請幫我找出提前
你有沒有檢查你的日誌? – 2015-01-15 16:29:01