-1
可能重複:
What can I do to avoid a NullPointerException?的Java NullPointerException異常上的createStatement
我開發一個餐廳的應用程序。當我嘗試初始化某個類時發生該錯誤。這是代碼。
public class DbItem {
private static Connection conn = null;
static {
conn = DBConnection.connect();
}
public static ArrayList<Item> fetchAll() {
ArrayList<Item> items = new ArrayList<>();
String sql = "select * from itens";
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
items.add(new Item(rs.getString("nome"), rs.getString("descricao"), rs.getFloat("preco")));
}
return items;
} catch (SQLException ex) {
Logger.getLogger(DbItem.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
的連接是從該類
public class DBConnection {
private static Connection conn;
public static Connection connect() {
if(conn == null) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "restaurante_comandas_jonnathan";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to " + dbName + " with " + userName);
JOptionPane.showMessageDialog(null, conn == null);
return conn;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
return null;
}
}
我試着用彈出對話框調試拍攝。我在返回命令之前檢查連接是否爲空,並且發現不是。然後,我檢查了第一個腳本的調用之後,發現它確實是空的。現在,如果一個對象不在返回之前,對象在檢索後如何可以爲空?
編輯:
這是它。堆棧跟蹤
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at model.data.DbItem.fetchAll(DbItem.java:48)
at model.Item.getAll(Item.java:76)
at view.PedidoForm.<init>(PedidoForm.java:22)
at view.Login$2.run(Login.java:99)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
你嘗試過用調試器附着?粘貼你的堆棧跟蹤... –
我其實不知道如何使用調試器。我的大部分時間都使用純文本編輯器。 –
現在可能是投入一些努力和學習的時候了。您可以免費下載IntelliJ IDE並調試您的代碼。它是一個Web應用程序或一個普通的Java程序? –