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();
}
}