在eclipse中連線資料庫並進行資料庫操作時出現空指標異常類java.lang.NullPointerException
java.lang.NullPointerException
載入驅動成功!
連線資料庫成功!
at com.dao.BookDAO.create(BookDAO.java:24)
at servlets.Insert_Book_Servlet.doPost(Insert_Book_Servlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
出現異常的位置(紅色):
public void create(BookInfo book) throws Exception {
// TODO Auto-generated method stub
Connection con=null;
PreparedStatement pst=null;
try{
con=DbConnection.getDBconnection();
pst=con.prepareStatement(INSERT_SQL);
pst.setString(1, book.getBookID());
pst.setString(2, book.getBookName());
pst.setString(3, book.getAuthor());
pst.setDouble(4, book.getPrice());
pst.setString(5, book.getRemarks());
pst.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
DbConnection.closeDB(con, pst, null);
}
}
原因:在getDbConnection()方法中沒有返回值或返回值為null
解決辦法:
public static Connection getDBconnection()
{
try{
Class.forName(driverName);
Connection con=DriverManager.getConnection(dbUrl, userName, userPwd);
System.out.println("載入驅動成功!");
System.out.println("連線資料庫成功!");
return con; //在連線資料庫時要記得返回con,否則會報空指標異常;上述異常之所以會發生就是因為我之前沒有返回值
}catch(Exception e){
e.printStackTrace();
System.out.println("載入驅動失敗!");
System.out.println("連線資料庫失敗!");
}
return null;
}