目录
DBCP数据库连接池实现步骤
创建properties文件
在连接之前,我们需要创建一个 properties 文件来存储数据库基本信息
driverClassName=com.mysql.cj.jdbc.Driver
// mysql-connector-java-5-bin.jar 驱动为 com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=XXXXX
实现代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import javax.xml.transform.Source;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;
public class DBCPTest {
private static DataSource source;
static {
try {
Properties pros = new Properties();
FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
pros.load(is);
source = BasicDataSourceFactory.createDataSource(pros);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection testGetConnection() throws Exception {
Connection conn = source.getConnection();
return conn;
}
@Test
public void TestDbcp() throws Exception {
Connection testGetConnection = DBCPTest.testGetConnection();
System.out.println(testGetConnection);
}
}
运行代码,连接成功