Introduction
In this project, you will learn how to set up a Druid database connection pool and use it to retrieve data from a MySQL database. Druid is a popular open-source database connection pool that supports various database connections, including MySQL, PostgreSQL, Oracle, and more.
👀 Preview

🎯 Tasks
In this project, you will learn:
- How to set up the Druid database connection pool
- How to implement the
getConn()method to return a database connection from the Druid connection pool - How to retrieve data from the MySQL database using the Druid connection pool
🏆 Achievements
After completing this project, you will be able to:
- Configure and use the Druid database connection pool
- Interact with a MySQL database using a connection pool
- Apply best practices for managing database connections in a Java web application
Set Up the Druid Database Connection Pool
In this step, you will learn how to set up the Druid database connection pool to connect to a MySQL database.
Open the
DBUtil.javafile located in theorg.labex.utilpackage.In the
DBUtilclass, you need to add the following code:
private static DataSource dataSource;
{
try {
// Load the Druid configuration from the properties file
InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
properties.load(inputStream);
// Create a DruidDataSource based on the configuration
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
This code is responsible for loading the Druid configuration from the druid.properties file and creating a DruidDataSource object based on the configuration.
- Implement the
getConn()method in theDBUtilclass to return a database connection from the Druid connection pool:
public Connection getConn() {
// Get a connection from the DruidDataSource
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
This method will return a database connection from the Druid connection pool.
Start the Web Application
In this step, you will learn how to launch the web application and view user information on your browser.
- In your terminal, navigate to the project directory using the following command:
cd ~/project/DruidProject
- Run the following command to start the web application:
mvn clean tomcat7:run
- Open a web browser and go to
http://localhost:8080. You will see an input field and a button, in the input field you can enter eitherAnyaorEthanand click the search button to retrieve data from the database.
The expected result should look like the figure below:

Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



