1. 程式人生 > >DBUtils的簡單封裝示例

DBUtils的簡單封裝示例

 版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/qq_40348465/article/details/83662643

  Commons DbUtils是Apache組織提供的一個對JDBC進行簡單封裝的開源工具類庫,使用它能夠簡化JDBC應用程式的開發,同時也不會影響程式的效能。

  DBUtils封裝了對JDBC的操作,簡化了JDBC操作,可以少寫程式碼。

DbUtils 關閉連結等操作

QueryRunner 進行查詢的操作

org.apache.commons.dbutils.handlers

ArrayHandler :將ResultSet中第一行的資料轉化成物件陣列

ArrayListHandler將ResultSet中所有的資料轉化成List,List中存放的是Object[]

BeanHandler :將ResultSet中第一行的資料轉化成類物件

BeanListHandler :將ResultSet中所有的資料轉化成List,List中存放的是類物件

ColumnListHandler :將ResultSet中某一列的資料存成List,List中存放的是Object物件

KeyedHandler :將ResultSet中存成對映,key為某一列對應為Map。Map中存放的是資料

MapHandler :將ResultSet中第一行的資料存成Map對映

MapListHandler :將ResultSet中所有的資料存成List。List中存放的是Map

ScalarHandler :將ResultSet中一條記錄的其中某一列的資料存成Object

org.apache.commons.dbutils.wrappers

SqlNullCheckedResultSet :對ResultSet進行操作,改版裡面的值

StringTrimmedResultSet :去除ResultSet中中欄位的左右空格。Trim()

主要方法:

DbUtils類:啟動類,jdbc輔助方法的集合類,執行緒安全。

QueryRunner類:執行SQL語句的類,可以設定查詢結果集的封裝策略,執行緒安全。

ResultSetHandler介面:轉換型別介面,將封裝結果集中的資料,轉換到另一個物件。

MapListHandler類:實現類,把記錄轉化成List。

BeanListHandler類:實現類,把記錄轉化成List,使記錄為JavaBean型別的物件。

 

簡單封裝示例:

1.首先匯入包:commons-dbutils-1.7.jar;mysql-connector-java-8.0.11.jar(也可以用其他版本的)

 

2.配置META-INF下的contex.xml檔案

如:

   mysql5用的驅動url是com.mysql.jdbc.Driver,mysql6以後用的是com.mysql.cj.jdbc.Driver。

<?xml version="1.0" encoding="UTF-8"?>
<Context>

  <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="" driverClassName="com.mysql.cj.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/hrsys1?serverTimezone=UTC"/>

</Context>

 

3.DataBaseHelper類(載入配置檔案,獲取Connection)

package com.bookms.util;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DataBaseHelper {
	public static Connection getConn() {
		try {
			//InitialContext()是用來載入配置檔案,獲取web容器配置的資料來源
			//InitialContext的構造方法主要是準備JNDI的訪問環境,如果不加引數,那就意味著是用本地匿名訪問
			/*JNDI(Java Naming and Directory Interface,Java命名和目錄介面)是一組在Java應用中訪問命名和目錄服務的API。
			命名服務將名稱和物件聯絡起來,使得我們可以用名稱訪問物件。目錄服務是一種命名服務,在這種服務裡,物件不但有名稱,還有屬性。*/
			Context initContext = new InitialContext();
			//一般情況下,intial.lookup("")中的引數就是JNDI名稱。但是用的應用伺服器,是把JNDI名放到java:comp/env/ejb/後面的。
			//Tomcat容器配置的JNDI需要加固定字首才是可查詢JNDI,需要加字首"java:comp/env/"。
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/mysql");
			Connection conn = ds.getConnection();
			return conn;
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// etc.
		return null;
	}
}

 

 4.DoBusiness(具體的封裝)

 

package com.HR.app.model;

import java.sql.Connection;
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.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.HR.app.entity.Employee;
import com.HR.app.util.DataBaseHelper;

/*
 * DAO 
 * data access object
 * 	資料存取物件
 */
public class DoBusiness {

	private Connection conn;
	QueryRunner run = new QueryRunner();

	public List<Employee> getDatas() {
		conn = DataBaseHelper.getConn();
		ResultSetHandler<List<Employee>> h = new BeanListHandler<Employee>(Employee.class);
		try {
			return run.query(conn, "select * from employee", h);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public boolean add(Employee emp) {
		conn = DataBaseHelper.getConn();
		try {
			return run.update(conn, "insert into employee values(?,?,?,?,?,?,?,?,?)", emp.getId(), emp.getName(),
					emp.getSex(), emp.getAdd(), emp.getPhone(), emp.getHireDate(), emp.getSal(), emp.getDept(),
					emp.getPwd()) > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	public boolean del(String id) {
		conn = DataBaseHelper.getConn();
		try {
			return run.update(conn, "delte from employee where id = ?", id) > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	public boolean modify(Employee emp) {
		conn = DataBaseHelper.getConn();
		try {
			return run.update(conn, "update employee set add = ?,phone = ?,sal = ?,dept = ?,pwd = ? where id = ?",
					emp.getAdd(), emp.getPhone(), emp.getSal(), emp.getDept(), emp.getPwd(), emp.getId()) > 0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

	public Employee getEmpById(String id) {
		conn = DataBaseHelper.getConn();
		ResultSetHandler<Employee> h = new BeanHandler<Employee>(Employee.class);
		try {
			return run.query(conn, "select * from employee where id = ?", h, id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	// 登陸驗證方法
	public Employee check(String id, String pwd) {
		conn = DataBaseHelper.getConn();
		ResultSetHandler<Employee> h = new BeanHandler<Employee>(Employee.class);
		try {
			return run.query(conn, "select * from employee where id = ? and pwd = ?", h, id, pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
}