BasicDatasource
Create a simple BasicDataSource object
With this example we are going to demonstrate how to create a simple org.apache.commons.dbcp.BasicDataSource
object, that is the basic implementation of javax.sql.DataSource that is configured via JavaBeans properties. In short, to create a simple BasicDataSource
object you should:
- Create a
BasicDataSource
object and configure the database. UsesetDriverClassName(String driverClassName)
method to set the jdbc driver class name. UsesetUrl(String url)
method to set the url. UsesetUsername(String username)
andsetPassword(String password)
to set the username and the password. - Use the
getConnection()
method ofBasicDataSource
to get the Connection for the database. - Use the
prepareStatement(String sql)
API method of Connection to create a PreparedStatement object for sending parameterized SQL statements to the database. - Use
executeQuery()
API method of PreparedStatement to execute the SQL query in this PreparedStatement object and return the ResultSet object generated by the query. Print the values of the ResultSet. - Close both the Connection and the PreparedStatement.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import org.apache.commons.dbcp.BasicDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SimpleBasicDataSource { public static void main(String[] args) throws Exception { // Create a BasicDataSource object and configure database BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/testdb"); dataSource.setUsername("root"); dataSource.setPassword("root"); Connection conn = null; PreparedStatement stmt = null; try { // Get connection and execute a simple query conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM users"); ResultSet rs = stmt.executeQuery(); // Print fetched data while (rs.next()) { System.out.println("Username : " + rs.getString("username")); } } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } } }
Output:
Username : Byron
Username : Ilias
Username : Nikos
Username : Dimitris
This was an example of how to create a simple BasicDataSource
object in Java.
how to set show_sql with dbcp