gpt4 book ai didi

java - 使用c3p0池连接数据库mysql

转载 作者:行者123 更新时间:2023-11-29 08:51:44 25 4
gpt4 key购买 nike

ComboPooledDataSource cpds = new ComboPooledDataSource(); 
cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver

cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/dragon" );
cpds.setUser("root");
cpds.setPassword("password");
cpds.setMaxPoolSize(50);

我创建了一个包含以下代码的 java 文件来配置 ComboPooledDataSource 对象。现在这段代码足以与数据库建立池连接吗?

如果没有,我还应该做什么?

还请告诉我如何在这里实现 JNDI。

请解释一下,因为我是初学者。

最佳答案

首先...创建代码以在包含静态方法或变量的类中启动连接,如下所示..

        private static ComboPooledDataSource cpds = new ComboPooledDataSource();
public static void MakePool()
{
try
{
cpds=new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/att_db");
cpds.setUser("root");
cpds.setPassword("dragon");
cpds.setMaxPoolSize(MaxPoolSize);
cpds.setMinPoolSize(MinPoolSize);
cpds.setAcquireIncrement(Accomodation);
}
catch (PropertyVetoException ex)
{
//handle exception...not important.....
}

}
public static Connection getConnection()
{
return cpds.getConnection();
}

完成后创建另一个用于服务器操作的类....

并从池中获取连接...

         try{

con=DatabasePool.getConnection();
// DatabasePool is the name of the Class made earlier....
.
.
.
. // Server operations as u wanted.....
.
.
}
catch(SQL EXCEPTION HERE)
{
.....
}
finally
{
if(con!=null)
{
con.close();
}
}

关于java - 使用c3p0池连接数据库mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com