每一次连接数据库,使用完成后,都必须要关闭吗?不关闭会有什么后果

解决方案 »

  1.   

     最严重的后果就导致机器内存溢出了。<a href="http://www.wangzhongyuan.com/archives/227.html" target="_bank">http://www.wangzhongyuan.com/archives/227.html</a> 可以看看这个
      

  2.   

    要关闭的。 使用try{创建连接;}catch()finally{关闭连接;}
      

  3.   

    最简单的一个连接过程:import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;/**
     * DAO基础类,负责创建和销毁数据库连接
     * @author liubowin
     *
     */
    public class BaseDAO {
    private String url = "jdbc:sqlserver://localhost:1433;database=testDB";
    private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private String userName = "sa";
    private String password = "sa";

    protected Connection conn = null;
    protected PreparedStatement ps = null;
    protected ResultSet rs = null; /**
     * 构造函数,负责加载驱动程序
     */
    public BaseDAO() {
    try {
    Class.forName(driver);
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    } /**
     * 获得Connection连接
     * @throws SQLException SQL异常
     */
    protected void getConnection() throws SQLException{
    conn = DriverManager.getConnection(url, userName, password);
    } /**
     * 关闭所有资源
     */
    protected void closeAll(){
    if(rs != null){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    rs = null;
    }
    }
    if(ps != null){
    try {
    ps.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    ps = null;
    }
    }
    if(conn != null){
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    conn = null;
    }
    }
    }}
    连接数据库是一个很浪费资源的过程,所以用完后必须关闭!上面的关闭数据库连接的方式,我认为大家应该借鉴。