DBConn.java

package apple;
import java.sql.*;

public class DBConn
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url="jdbc:mysql://localhost:3306/joke?user=root";

public DBConn()
{
try
{
Class.forName(
"com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/joke?user=root");
}
catch(Exception e)
{
e.printStackTrace();
}
}


public Connection getConnection() throws SQLException
{
Connection conn = null;
conn = DriverManager.getConnection(url);
return conn;
}

public boolean closeConn()
{
try{
if(conn!=null) conn.close();
return true; }
catch (SQLException e) {
System.err.println(
"closeConn:"+e.getMessage());
return false; }
}
}

下面是我测试的数据库连接和释放连接的代码,使我想不明白的是最后两句,为什么需要我执行两句才能关闭数据库连接呢?

<%@page contentType=
"text/html;charset=gb2312"%>
<%@page import=
"apple.*" %>
<%
DBConn dataconn =new DBConn();
java.sql.Connection conn =dataconn.getConnection();
java.sql.Statement stmt =conn.createStatement();
java.sql.ResultSet rs=stmt.executeQuery(
"select * from secondnews");

while(rs.next())
{
%>
<%=rs.getString(1)%>

<%=rs.getString(2)%>
<%

}
conn.close();
dataconn.closeConn();
%>
Jason   2004-12-08 15:36:34 评论:3   阅读:2082   引用:0
无题 @2004-12-09 16:23:29  xiaosheng
rs.close只是关闭结果集,不关闭连接!其实只要关闭conn,rs、stmt也自动关闭。
你说的不错! @2004-12-08 18:49:50  XIAOSHENG
当时我查看连接的进程,执行它不产生连接,所以我觉得没有必要去关闭它!
我觉得 @2004-12-08 17:51:39  idiot
我觉得你的close方法有问题
关闭的时候不仅仅只关闭conn.close()
还有stmt.close()
rs.colse()
诸如此类的东东

public boolean closeConn()
{
try{
if(conn!=null) conn.close();
if(stmt!=null) stmt.close();
if(rs!=null) rs.close();

return true; }
catch (SQLException e) {
System.err.println("closeConn:"+e.getMessage());
return false; }
}
}


还有就是你在jsp中只用调用dataconn.closeConn();
就可以了

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

小圣空间 版权没有 盗版必就