板橋你說:“資料庫關閉之後可以使用resulset訪問,我以前一直這麼做,我都是使用PrepareStatement”。為什麼我的程式碼在jsp頁面裡提

smallduzi發表於2002-10-16
板橋你說:“資料庫關閉之後可以使用resulset訪問,我以前一直這麼做,我都是使用PrepareStatement”。為什麼我的程式碼在jsp頁面裡提示資料庫已關閉。

SQLHelper.java
package com.pingod.database;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import com.pingod.sql.ConnectionPool;

public final class SQLHelper {
	
	private ConnectionPool pool = null;
	private Connection con = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	
	public SQLHelper(){
		pool = ConnectionPool.getInstance();
	}
	
	public ResultSet userDbQuery() throws SQLException{
		con = pool.getConnection();
		String sql = "select tempid,username,password from tempuser where 1 = ?";
		pstmt = con.prepareStatement(sql);
		pstmt.setInt(1,1);
		rs = pstmt.executeQuery();
		pstmt.close();//我把這行和下面那行註釋掉query.jsp就可以顯示了,否則提示[Microsoft][SQLServer JDBC Driver]Object has been closed.

		con.close();
		return rs;
	}

	
}

query.jsp
<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="java.util.*, java.sql.*, java.text.*"%>
<%@ page import="com.pingod.database.SQLHelper"%>
<%!
ResultSet rs = null;
%> 
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY leftmargin="5" topmargin="8" bgcolor="FFFFFF" text="#000000">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr> 
    <td>id</td>
    <td>username</td>
    <td>password</td>
  </tr>
<%
SQLHelper sqlHelper = new SQLHelper();
rs = sqlHelper.userDbQuery();
while(rs.next()){
  String id = rs.getString(1);
  String username = rs.getString(2);
  String password = rs.getString(3);
%>
  <tr> 
    <td><%=id%></td>
    <td><%=username%></td>
    <td><%=password%></td>
  </tr>
<%
}
%>
</table>
</BODY>
</HTML>

我的程式碼那裡錯了,請多指教!

相關文章