我们使用JDBC的标准代码部分是...

Connection conn = getConnection(...);
Statement  stmt = conn.conn.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE,
                                                ResultSet.CONCUR_READ_ONLY);
ResultSet  rset = stmt.executeQuery (sqlQuery);

// do stuff with rset

rset.close(); stmt.close(); conn.close();

Question 1:使用连接池时,是否应该在最后关闭连接?如果是这样的话,合并的目的不是已经失go 了吗?如果没有,数据源如何知道某个特定的连接实例何时被释放并可以重用?我对这一点有点困惑,任何指点都很感激.

Question 2:以下方法是否接近标准?看起来像是试图从池中获取连接,如果无法建立数据源,请使用老式的DriverManager.我们甚至不确定在运行时执行哪个部分.

synchronized public Connection getConnection (boolean pooledConnection)
                                                        throws SQLException {
        if (pooledConnection) {
                if (ds == null) {
                        try {
                                Context envCtx = (Context)
                                        new InitialContext().lookup("java:comp/env");
                                ds = (DataSource) envCtx.lookup("jdbc/NamedInTomcat");
                                return ds.getConnection();
                        } catch (NamingException e) {
                                e.printStackTrace();
                }}
                return (ds == null) ? getConnection (false) : ds.getConnection();
        }
        return DriverManager.getConnection(
                "jdbc:mysql://"+ipaddy+":"+dbPort +"/" + dbName, uName, pWord);
}

编辑:我认为我们得到了池连接,因为我们没有看到堆栈跟踪.

推荐答案

When using Connection Pool, should one close the Connection at the end? If so, isn't the purpose of pooling lost? And if not, how does the DataSource know when a particular instance of Connection is freed up and can be reused? I am a little confused on this one, any pointers appreciated.

是的,您当然也需要关闭池连接.它实际上是实际连接的包装.它会将实际连接释放回池中.由池进一步决定是关闭实际连接,还是重新用于新的getConnection()呼叫.因此,无论您是否使用连接池,您都应该在try块中的finally块中以相反的顺序关闭所有JDBC资源,在try块中您获取了它们.在Java7中,使用try-with-resources语句可以进一步简化这一点.


Is the following method anything close to standard? Looks like an attempt to get a connection from the pool, and if DataSource cannot be established, use the old fashioned DriverManager. We are not even sure which part is getting executed at runtime. Repeating the question above, should one close the Connection coming out of such a method?

这个例子很吓人.在应用程序启动期间,只需在应用程序范围的DB config类的某个构造函数/初始化中查找/初始化DataSource.然后,在应用程序的剩余生命周期中,只需对同一个数据源调用getConnection().不需要同步或空值判断.

另见:

Mysql相关问答推荐

优化使用ORDER BY加载耗时较长的MySQL请求

如果WHERE语句包含所有列,唯一键顺序是否重要?

无法删除或更新父行:外键约束无法删除表

MySQL多次联接同一个表使计数变得奇怪

MySQL工作台的编码问题

PythonAnywhere中SSH到MySQL数据库无限期挂起,SSH正确,workbench可以完美连接

Group_CONCAT CASE 乘法输出

如何对 varchar() 数据值使用聚合窗口函数?

从连接表中try 按唯一ID计算行数 MySQL

MySQL 关于 JSON 数组和子查询的问题

如何用sql找出两次之间的差异

MySQL - 单词边界的正则表达式,不包括下划线(连接标点符号)

MySql,如何从列中替换某种格式的字符串

使用数据表的直方图(SQL 查询)

查询给出错误时的 mySQL Group_Concat 和 Case

mysql从另一个表中 Select 不相等的值

索引和多列主键

MySQL Partitioning / Sharding / Splitting - 走哪条路?

MySQL术语约束与外键的区别?

如何将本地托管的 MySQL 数据库与 docker 容器连接