2013-07-03 115 views
0

NullPointerException異常,當我嘗試從JavaBean中連接到MySQL數據庫NullPointerException異常

org.apache.jasper.JasperException: An exception occurred processing JSP page  /ShowProductCatalog.jsp at line 9 
<jsp:useBean id= "data" class= "cart.ProductDataBean" scope="request"/> 

<html> 
    <body> 
8:  <body> 
9:   <% List productList = data.getProductList(); 
10:    Iterator prodListIterator = productList.iterator(); 
11:   %> 

根源

java.lang.NullPointerException 
    cart.ProductDataBean.getProductList(ProductDataBean.java:36) 

ProductDataBean.java

public ProductDataBean() 
    { 
     try 
     { 
       String userName = "root"; 
       String password = "root"; 
       String url = "jdbc:mysql://localhost:/eshopdb"; 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     connection = DriverManager.getConnection(url,userName,password); 
       System.out.println("Database connection established"); 
     }catch(Exception e){e.printStackTrace();} 
    } 

    public static Connection getConnection() 
    { 
     return connection; 
    } 



public ArrayList getProductList() throws SQLException 
     { 
      ArrayList productList = new ArrayList(); 
/**********************HERE IS LINE 36. ERROR HERE*******************************/ 
      Statement statement = connection.createStatement();//ERROR HERE 
      ResultSet results = statement.executeQuery("SELECT * FROM product"); 

     Help 
連接到MySQL數據庫

回答

0

如果connection在分配給它後立即爲空。 (你打印「建立數據庫連接」的位置)我懷疑它是,並且你確實想要調試那個DriverManager.getConnection調用。另外,您確定catch(Exception e){e.printStackTrace();}未開火嗎?

+0

我玩過if語句。我認爲這個連接是空的。我怎樣才能解決這個問題 – mbass

+0

雖然Javadoc文檔的getConnection(http://docs.oracle.com/javase/6/docs/api/java/sql/DriverManager.html#getConnection(java.lang.String,java.lang中。 String,java.lang.String))並沒有真正地說它可以返回null,它聽起來像是在它無法連接到數據庫時那樣做。如果你刪除「本地主機」或明確冒號後會發生什麼讓「本地主機:3306」(默認端口)? –

+0

還看到:http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html –