Introduction to DBUtils and first Demo with CRUD operations

Apache Commons DbUtils library is a quite small set of classes which are designed to make easier JDBC call processing without resource leak and to have cleaner code.

There are following six steps involved in building a JDBC application −

  • Import the packages − Requires that we include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.

  • Register the JDBC driver − Requires that we initialize a driver so we can open a communication channel with the database.

  • Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.

  • Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.

  • Extract data from result set − Requires that we use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.

  • Clean up the environment − Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

1. Create Employee table

mysql> use emp;
mysql> create table Employees
    -> (
    -> id int not null,
    -> age int not null,
    -> first varchar (255),
    -> last varchar (255)
    -> );
Query OK, 0 rows affected (0.08 sec)
mysql>


2. Create Data Record

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)

mysql>

3. Employee.java

 

public class Employee {
   private int id;
   private int age;
   private String first;
   private String last;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getFirst() {
      return first;
   }
   public void setFirst(String first) {
      this.first = first;
   }
   public String getLast() {
      return last;
   }
   public void setLast(String last) {
      this.last = last;
   }
}

 

4. MainApp.java

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

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

public class MainApp {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/emp";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "admin";

   public static void main(String[] args) throws SQLException {
      Connection conn = null;
      QueryRunner queryRunner = new QueryRunner();
      
      //Step 1: Register JDBC driver
      DbUtils.loadDriver(JDBC_DRIVER);

      //Step 2: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      //Step 3: Create a ResultSet Handler to handle Employee Beans
      ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);

      try {
         Employee emp = queryRunner.query(conn, "SELECT * FROM employees WHERE first=?",
            resultHandler, "Sumit");
         //Display values
         System.out.print("ID: " + emp.getId());
         System.out.print(", Age: " + emp.getAge());
         System.out.print(", First: " + emp.getFirst());
         System.out.println(", Last: " + emp.getLast());
      } finally {
         DbUtils.close(conn);
      }              
   }
}

 

The main code structure is shown as above, for C R U D operations,

we only need to make slight changes .

5. Create

String insertQuery ="INSERT INTO employees(id,age,first,last)  VALUES (?,?,?,?)";
int insertedRecords = queryRunner.update(conn, insertQuery,104,30, "Sohan","Kumar");

6. Read

ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);
Employee emp = queryRunner.query(conn, "SELECT * FROM employees WHERE first=?", resultHandler

7. Update

String updateQuery = "UPDATE employees SET age=? WHERE id=?";
int updatedRecords = queryRunner.update(conn, updateQuery, 33);

8. Delete

String deleteQuery = "DELETE FROM employees WHERE id=?";
int deletedRecords = queryRunner.delete(conn, deleteQuery, 33);

 

posted @ 2019-05-29 17:02  CodingYM  阅读(235)  评论(0编辑  收藏  举报