进入首页的时候偶尔会报空指针错误,网上查了一下虽然知道是数据库连接问题,但是不知道如何解决。首页需要多次查询数据库得出不同表的数据到页面呈现,其他单次查询的页面就不会报这样的错。有人指导一下么
servlet:
dao(其他一样我就贴一段):
数据库连接工具:
public class DBUtil {
private static Connection conn;
private static Statement stmt;
private static PreparedStatement pstmt ;
private static DBUtil instance = new DBUtil();
private DBUtil() {}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static DBUtil getInstance() {
return instance;
}
public static Connection getConnection() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xchcxxgl", "root", "a+123456");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public Statement getStatement() {
Connection conn = getConnection();
try {
if(conn != null) {
stmt = conn.createStatement();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stmt;
}
public static PreparedStatement getPreparedStatement(String sql) {
Connection conn = getConnection();
try {
if(conn != null) {
pstmt = conn.prepareStatement(sql);
}
}catch(SQLException e) {
e.printStackTrace();
}
return pstmt;
}
public static void closeDBResources() {
try {
if(pstmt != null && !pstmt.isClosed()) {
pstmt.close();
}
if(stmt != null && !stmt.isClosed()) {
stmt.close();
}
if(conn != null && !conn.isClosed()) {
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}