一个你们自己觉得好的。这个Connection应该调用一次就要关吗?

解决方案 »

  1.   

    这个要看你的程序的需要了, 有的一个Connection在短时间内很可能需要多次使用, 这种就可保持长时间.
    如果是偶尔用一下Connection, 那么在使用后就关闭掉吧.
      

  2.   

    package cn.mldn.lxh.dbc ;
    import java.sql.* ;// 主要功能就是连接数据库、关闭数据库
    public class DataBaseConnection
    {
    private final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ;
    private final String DBURL = "jdbc:oracle:thin:@localhost:1521:MLDN" ;
    private final String DBUSER = "scott" ;
    private final String DBPASSWORD = "tiger" ;
    private Connection conn = null ; public DataBaseConnection()
    {
    try
    {
    Class.forName(DBDRIVER) ;
    this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
    }
    catch (Exception e)
    {
    }
    } // 取得数据库连接
    public Connection getConnection()
    {
    return this.conn ;
    } // 关闭数据库连接
    public void close()
    {
    try
    {
    this.conn.close() ;
    }
    catch (Exception e)
    {
    }
    }
    };
      

  3.   

    sql server的连接可以随意关闭,好像ms就给连接实现成那样,用一次关一次
    不过orcl的连接就要谨慎了,最好做个连接池,可以使用Database connection pooling services.
    DBCP这个类库已经比较稳定,参考http://commons.apache.org/dbcp/
      

  4.   

    至于连接的使用规范,可以参考任何一个数据库的jdbc使用样例,这里我贴的是mysql的,原文可
    以参考http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-examples-connection-drivermanager
    // assume that conn is an already created JDBC connection
    Statement stmt = null;
    ResultSet rs = null;try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT foo FROM bar");    // or alternatively, if you don't know ahead of time that
        // the query will be a SELECT...    if (stmt.execute("SELECT foo FROM bar")) {
            rs = stmt.getResultSet();
        }    // Now do something with the ResultSet ....
    } finally {
        // it is a good idea to release
        // resources in a finally{} block
        // in reverse-order of their creation
        // if they are no-longer needed    if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) { // ignore }        rs = null;
        }    if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException sqlEx) { // ignore }        stmt = null;
        }
    }