0
我知道這是一個小問題,但請給我一個想法爲什麼下面提到的代碼拋出NullPointerException?以下一個順序執行初始化:靜態字段/初始化程序 - 構造函數 - 局部變量。爲什麼在調用addInvoiceData()時,所有靜態變量(連接和語句)都已經初始化,我有異常?如果我在方法中連接到數據庫,那麼一切都可以實現。任何意見將不勝感激。在構造函數中的JDBC連接
public class DaoClass {
public DaoClass() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved_project", "root", "1111");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
static Connection connection;
static PreparedStatement statement;
public static void addInvoiceData() {
try {
statement = connection.prepareStatement("INSERT INTO invoices(contractor_id, invoice_num, date, amount) VALUES (?, ?, ?, ?)");
statement.setInt(1, 1);
statement.setString(2, "RM-2014");
statement.setString(3, "20140212");
statement.setFloat(4, 125.12f);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {statement.close();}
if (connection != null) {connection.close();}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
addInvoiceData();
}
}