如何关闭 JNDI 连接?

How to close JNDI connection?

我正在使用 JNDI 进行数据库连接。我在 META-INF 中创建了一个 XML 文件用于连接。

<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for each web application -->
<Context crossContext="true">

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <Resource name="jdbc/myDB" auth="Container"
        type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="600000"
        username="root" 
        password="abc123" 
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/game"/>
</Context>

在 java class 中,我使用以下代码获取连接

    Context envContext;
    Datasource ds;
    envContext = new InitialContext();
    Context initContext  = (Context)envContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)initContext.lookup("jdbc/myDB");
    Connection con=ds.getConnection();

但是,我该如何关闭连接?

DataSource 将负责管理与数据库的物理连接。当您调用con.close(这是必须)时,物理连接将返回到池中并将连接设置为睡眠状态。如果连接关闭,DataSource 将负责获取新连接(如果可能)。

简而言之,您不必担心关闭物理连接。