Apache DBUtils Tutorial

DBUtils BeanListHandler Example

package com.test.dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class DBUtilsWithConnection {

   
public static void main(String[] args) throws SQLException {

       
final String url = "jdbc:mysql://localhost:3306/test";
       
final String driver = "com.mysql.jdbc.Driver";
       
final String usr = "root";
       
final String pwd = "root";

        QueryRunner run =
new QueryRunner();

        DbUtils.loadDriver
(driver);
        Connection conn = DriverManager.getConnection
(url, usr, pwd);
       
// -----------------------------------------------------------------------------------
       
ResultSetHandler<List<Employee>> resultListHandler = new BeanListHandler<Employee>(Employee.class);

       
try {
           
List<Employee> empList = run.query(conn, "SELECT * FROM employee", resultListHandler);
            System.out.println
(empList);
       
} finally {
           
DbUtils.close(conn);
       
}

    }
}
Output
[Employee [employeeId=1, employeeName=Rockey], Employee [employeeId=2, employeeName=Jose]]

DBUtils MapListHandler Example

package com.test.dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class DBUtilsWithConnection {

   
public static void main(String[] args) throws SQLException {

       
final String url = "jdbc:mysql://localhost:3306/test";
       
final String driver = "com.mysql.jdbc.Driver";
       
final String usr = "root";
       
final String pwd = "root";

        QueryRunner run =
new QueryRunner();

        DbUtils.loadDriver
(driver);
        Connection conn = DriverManager.getConnection
(url, usr, pwd);
       
// -----------------------------------------------------------------------------------
       
       
try {
           
List<Map<String, Object>> maps = run.query(conn, "SELECT * FROM employee", new MapListHandler());
            System.out.println
(maps);
       
} finally {
           
DbUtils.close(conn);
       
}

    }
}
Output
[{EMPLOYEEID=1, EMPLOYEENAME=Rockey, EMPLOYEE_ADDRESS=1}, {EMPLOYEEID=2, EMPLOYEENAME=Jose, EMPLOYEE_ADDRESS=2}]




Previous 1 2 3 4 Next








3 Responses to "Apache DBUtils Tutorial"
  1. Jim E 2014-03-01 08:57:19.0
  1. admin 2014-03-02 08:57:19.0
  1. Chon Nguyen 2018-01-02 22:43:03.0

Your email address will not be published. Required fields are marked *