我在contex.xml中编写:

<Resource name="1_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/1_db">
<Resource name="2_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/2_db">
<Resource name="3_db" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/3_db">
<Resource name="common" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="root" password="tunespray2008" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/common">


Java代码:

public static Connection getDBConnection(String url)
{
Connection con = null;
    try
    {
    Context ctx = new InitialContext();
    BasicDataSource ds = (BasicDataSource)tx.lookup("java:comp/env/"+url);
    con = ds.getConnection();
    }catch(Exception e) {}
    return con;
}


之后,我打电话给:

String url ="common";
LoginDAO ldcom = DAOFactory.getLoginDAO(url);
url ="1_db";
LoginDAO ldcom = DAOFactory.getLoginDAO(url);
StatusDAO ldcom = DAOFactory.getStatusDAO(url);


之后,尽管我们称JProfilercon.close()rs.close(),但当我们浏览st.close()时,它显示了许多打开的连接。

请提及我们如何以正确的方式使用Datasource

最佳答案

有2个点:

1)在finally块中始终关闭连接(和其他数据库资源)。您的情况可能是:

Connection conn = null;
try {
    conn = getDBConnection(xxx);
    // do stuff with the connection
}
// optionally catch any errors that you can handle
finally {
    // close other DB resources that depend on conn, e.g. Statements, ResultSets
    if( conn != null ) try { conn.close(); }
    catch(Exception ignore) {}
}


2)您看到的打开的连接可能是连接池。使用DriverManager.getConnection()创建数据库连接是一个昂贵(耗时)的过程。在存在许多并发请求的应用服务器环境中,为每个请求创建新连接将是性能的杀手。 javax.sql.Datasource包装由应用程序服务器管理的连接池。当您close()从该池(Datasource)获得的连接不会被破坏,而是返回到池中以备将来使用。

10-06 05:47
查看更多