首页 > 解决方案 > c3p0 连接池无法更改数据库

问题描述

我正在运行一个涉及 3 个数据库的 Web 应用程序,第一个数据库是管理数据库,另外两个数据库用于两个独立的机构,这意味着两个机构都使用同一个应用程序,但可以根据输入的 unique_code 访问各自的数据库。数据库是 starter(管理数据库)、company1 和 company2。

当 Web 应用程序启动时,管理数据库最初会自动连接。(起始数据库)。(第一个连接池)代码如下:完美运行。

comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://host.com/starter");
comboPooledDataSource.setUser("username");
comboPooledDataSource.setPassword("password");                       
comboPooledDataSource.setMinPoolSize(2);
comboPooledDataSource.setMaxPoolSize(3000);
comboPooledDataSource.setAcquireIncrement(1);
comboPooledDataSource.setMaxIdleTime(1800);
comboPooledDataSource.setMaxStatements(0);
comboPooledDataSource.setIdleConnectionTestPeriod(3);
comboPooledDataSource.setBreakAfterAcquireFailure(false);
comboPooledDataSource.setUnreturnedConnectionTimeout(5);

并且用户必须在主页的文本字段中输入代码(如登录)。如果代码存在于起始数据库中,则与代码相关的数据库已连接,用户可以从该数据库查看其内容。

//获取数据库名称的代码写在下面:这也成功

String entry_code=request.getParameter("Ecode");
 //where 'Ecode' is the name of the html textfield where the user types the code
 try{
 con=Main_C3Po_Connection.getInstance().getConnection();
 String sql="select db from checker where code='"+entry_code+"'";
 pst=con.prepareStatement(sql);
 rs=pst.executeQuery();
 if(rs.next()){
get_db=rs.getString("db");
 }
 
 }catch(SQLException e){
 out.println(e);
 }

eg: starter(admin database) 表名:checker
id | 代码 | 分贝 |
11 | 44 | 公司1 |
12 | 35 | 公司2 |

所以第二个连接池没有固定的数据库 url,而是一个可变的数据库名称。

eg:("jdbc:mysql://host.com/"+get_db+"?autoReconnect=true&useUnicode=yes");

其中get_db是变量名。
所以当用户输入代码44时,与输入的代码相关的db列的值为(company1),然后放入get_db变量中,即可连接数据库并可以访问。

当输入第一个代码(44)时, “ company1 ”值被放入“ get_db ”变量中,连接成功。

但问题是在注销并输入第二个代码(35)后,“company2”值也被放入“get_db”变量中,但连接池由于某种原因仍保持先前的数据库连接,无法切换到另一个选择的数据库
下面是无法切换到不同数据库的第二个连接池,尽管数据库变量已更改:

comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://host.com/"+get_db+"?autoReconnect=true&useUnicode=yes");
comboPooledDataSource.setUser("username");
comboPooledDataSource.setPassword("password");
comboPooledDataSource.setMinPoolSize(2);
comboPooledDataSource.setMaxPoolSize(3000);
comboPooledDataSource.setAcquireIncrement(1);
comboPooledDataSource.setMaxIdleTime(1800);
comboPooledDataSource.setMaxStatements(0);
comboPooledDataSource.setIdleConnectionTestPeriod(5);
comboPooledDataSource.setBreakAfterAcquireFailure(false);
comboPooledDataSource.setUnreturnedConnectionTimeout(5);

请我如何配置第二个连接池以在注销后终止所有连接,以便它可以**切换**并访问选择的任何其他数据库。谢谢你。

标签: javanetbeansc3p0

解决方案


这是一个尴尬的配置;我不推荐它。但它应该工作。打电话的动作

comboPooledDataSource.setJdbcUrl("jdbc:mysql://host.com/"+get_db+"?autoReconnect=true&useUnicode=yes");

应该会导致“软重置”,因此Connection您从池中获得的任何新 s 都将进入新数据库。你确定你不是还在用旧的Connection吗?也就是说,您是否确定close()所有Connection对象都从更改前开始?

一种不那么尴尬的方法是创建多个Connection池,一个用于您需要访问的每个数据库。使用完池后,通过调用池本身Connection释放线程和Connection与之关联的 s 。close()


推荐阅读