JSP中查询不稳定怎么解决?
在用JSP做网站的时候,为什么出现查询不稳定的情况!!就是说:输入同一个查询条件,有时候得到查询结果,有时候得不要查询结果,而数据库中有这样一条记录!有的时候甚至还出现空指针异常!!请问这是怎么回事??急!
以下为执行查询的控制器servlet!
String condition=request.getParameter( "condition ").trim();
String bookinfo=request.getParameter( "bookinfo ").trim();
BookMgr book=new BookMgr();
//Collection c;
//Book booklist;
if(condition.equals( "bookname "))
{
Collection c=book.searchByName(bookinfo);
if(c.isEmpty())
{
//没有找到指定的书
request.setAttribute( "error ", "没有找到符合条件的书,请重新选择查询条件!!! ");
request.getRequestDispatcher( "error.jsp ").forward(request, response);
}
else
{
request.setAttribute( "booklist ", c);
request.getRequestDispatcher( "list.jsp ").forward(request, response);
}
/*
while(bookinterator.hasNext())
{
booklist=(Book)bookinterator.next();
}
*/
}
if(condition.equals( "author "))
{
Collection c=book.searchByAuthor(bookinfo);
if(c.isEmpty())
{
//没有找到指定的书
request.setAttribute( "error ", "没有找到符合条件的书,请重新选择查询条件!!! ");
request.getRequestDispatcher( "error.jsp ").forward(request, response);
}
else
{
request.setAttribute( "booklist ", c);
request.getRequestDispatcher( "list.jsp ").forward(request, response);
}
}
if(condition.equals( "publish "))
{
Collection c=book.searchByPublish(bookinfo);
if(c.isEmpty())
{
//没有找到指定的书
request.setAttribute( "error ", "没有找到符合条件的书,请重新选择查询条件!!! ");
request.getRequestDispatcher( "error.jsp ").forward(request, response);
}
else
{
request.setAttribute( "booklist ",c);
request.getRequestDispatcher( "list.jsp ").forward(request, response);
}
}
if(condition.equals( "ISDN "))
{
//暂不支持这个查询方法,如果以ISDN来进行查询会抛出异常
throw new ServletException();
}
以下是BookMgr类是一个按书名执行查询的方法
/*
* task: 按书名进行模糊查询
* @param BookName要查询的书名
* @return返回Collection对象;
*/
public Collection searchByName(String BookName)
{
conn=DB.getConnection();
Collection c=new ArrayList();
String sql= "select * from book where BookName like '% "+BookName+ "% ' ";
try {
Statement stm=conn.createStatement();
ResultSet rs=stm.executeQuery(sql);
Book book;
while(rs.next())
{
book=new Book();
book.setID(rs.getInt( "id "));
book.setBookName(rs.getString( "BookName "));
book.setBookClass(rs.getInt( "BookClass "));
book.setAuthor(rs.getString( "Author "));
book.setPublish(rs.getString( "Publish "));
book.setBookNo(rs.getString( "BookNo "));
book.setContent(rs.getString( "Content "));
book.setPrice(rs.getFloat( "Price "));
book.setAmount(rs.getInt( "Amount "));
book.setLeft_Amount(rs.getInt( "Left_Number "));
book.setRegTime(rs.getDate( "RegTime "));
book.setPicture(rs.getString( "Picture "));
c.add(book);
book=null;
}
//rs.close();
//stm.close();
//conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c;
}
[解决办法]
//rs.close();
//stm.close();
//conn.close();
为什么注释掉?
[解决办法]
测试一下你每次查询前得到的条件吧
[解决办法]
//rs.close();
//stm.close();
//conn.close();
问题就出在这里,不能因为怕try catch麻烦就把关闭和数据库链接的操作屏蔽掉啊
这样会导致某些时候因为连接数据库的无效进程太多,导致新的链接数据库的进行连不上数据库
,数据库都连不上了,查询操作当然不能返回正确值