This example demonstrates how to use the BasicDataSource
class of Apache Commons DBCP to create a basic requirements for database connection. The configuration of the data source can be defined using some property method provided by this class. The basic properties are the driver classname, connection url, username and password.
After the datasource ready we can obtain a connection by calling the getConnection()
method of the datasource. This method might throw an SQLException
when errors occurs.
package org.kodejava.commons.dbcp;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BasicDataSourceExample {
public static void main(String[] args) throws Exception {
// Creates a BasicDataSource and defines its properties
// including the driver class name, jdbc url, username
// and password.
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:mysql://localhost/kodejava");
dataSource.setUsername("root");
dataSource.setPassword("");
// Get a connection from the data source and do a
// database query with the obtained connection.
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM authors")) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
We can simplify the code above so that we don’t have to close the PreparedStatement
and Connection
manually like we did in the finally
block in the code snippet. We can use try-with-resources
to automatically close resources. An example can be seen in the following example: How to automatically close resources in JDBC?.
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
</dependencies>
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023