NullPointerException异常
问题描述:
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数据库
答
如果connection
在分配给它后立即为空。 (你打印“建立数据库连接”的位置)我怀疑它是,并且你确实想要调试那个DriverManager.getConnection
调用。另外,您确定catch(Exception e){e.printStackTrace();}
未开火吗?
我玩过if语句。我认为这个连接是空的。我怎样才能解决这个问题 – mbass
虽然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”(默认端口)? –
还看到:http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html –