如何在运行时更改C3P0用户和密码

时间:2014-07-10 15:22:32

标签: java c3p0

当我开始时,我的配置是:user=test1&password=test1

我想将其更改为user=test2&password=test2

这是代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/config/spring/appcontext-test.xml" })
public class SingleDataSourceProcessorTest {

    @Autowired
    private ComboPooledDataSource masterDs;

    @Test
    public void test_c3p0_datasource_to_single_datasource()
            throws InterruptedException, SQLException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        query();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        query();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        Thread.sleep(3000);

         masterDs.setUser("test2");
         System.out.println("change username");
         masterDs.setPassword("test2");
         System.out.println("change password");

        Thread.sleep(3000);
    }

    private void query() throws SQLException {
        Connection conn = masterDs.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet result = stmt.executeQuery("select @@read_only");
        result.close();
        stmt.close();
        conn.close();
    }
}

我的春季配置:

<bean id="masterDs" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/db1" />
    <property name="user" value="test1" />
    <property name="password" value="test1" />
    <property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="minPoolSize" value="5" />
    <property name="maxPoolSize" value="25" />
</bean>

当代码仅更改user时,另一个线程使用错误的userpassword对来查询数据库并抛出异常。

那么如何在运行时更改userpassword

0 个答案:

没有答案