简单的三层框架以及使用dbutils进行数据库操作(入门)


1.       搭建三层框架

1.1.     什么是三层框架

三层框架就是将代码简单的分为三层并对某些地方进行必要的封装,方便日后维护,主要分为以下三部分:

界面层(Swing或JSP):主要是界面显示的代码。

业务层(business):主要是处理业务逻辑的代码。

数据访问层(DAO):主要是与数据库交互的代码。

 

1.2.     各层之间如何协作

 

关系:界面层(调用) à 业务层(调用)à 数据访问层(与数据库交互)

          (显示)界面层  ß  (结果)业务层  ß (结果)数据访问层

数据传递:各层之间将数据封装成实体类(entity)进行传递。

 

写入信息:界面层将用户录入的信息封装成实体类对象,然后传给业务层进行相关的业务处理,然后业务层选择需要调用的数据访问层,数据访问层负责将传递过来的实体对像中封装的信息提取出来,并且拼出SQL语句,将信息写入数据库。

 

显示信息:数据访问层将数据库中的数据提取出来封装成实体对象,如果有多个对象的话继而封装成集合,然后传递给调用它的业务层进行业务处理,业务层再将处理过的实体对象或是集合传递给调用业务层的界面,界面最后将实体对象或是集合中封装的信息提取出来进行显示。

===============================================================================

2.       编写实例(省略界面层和业务层)

 

需要的jar包:数据库直连包,dbutils包

数据库:stuDB

表:USERS

表结构:userId int NOT NULLIDENTITY(1,1) PRIMARY KEY,

           userName nvarchar(20) NOT NULL,

           password nvarchar(20) NOT NULL,

           realName nvarchar(20) ,

           sex nvarchar(2)

=========================================================

实体类:UsersEntity

view plaincopy to clipboardprint?

package com.saga.entity;  

 

/** 

 *USERS表的实体类 

 *@author saga1320 

*/ 

 

public class UsersEntity {    

      private int userId;  

     private String userName;  

     private String password;  

     private String realName;  

     private String sex;  

     public UsersEntity() {   

     }    

     public String getPassword() {  

          return password;  

     }  

     public void setPassword(String password) {  

          this.password = password;  

     }  

     public String getRealName() {  

          return realName;  

     }  

     public void setRealName(String realName) {   

          this.realName = realName;   

    }   

     public String getSex() {   

          return sex;   

     }   

     public void setSex(String sex) {    

          this.sex = sex;    

      }    

     public int getUserId() {  

          return userId;    

     }    

     public void setUserId(int userId) {    

          this.userId = userId;    

     }    

     public String getUserName() {    

          return userName;    

     }    

     public void setUserName(String userName) {    

          this.userName = userName;   

     }         

 

 

package com.saga.entity;

 

/**

 

 *USERS表的实体类

 

 *@author saga1320

 

*/

 

public class UsersEntity { 

 

     private int userId;

 

     private String userName;

 

     private String password;

 

     private String realName;

 

     private String sex;

 

     public UsersEntity() {

 

     }

 

     

 

     public String getPassword() {

 

          return password;

 

     }

 

     public void setPassword(String password) {

 

          this.password = password;

 

     }

 

     public String getRealName() {

 

          return realName;

 

     }

 

     public void setRealName(String realName) {

 

          this.realName = realName;

 

     }

 

     public String getSex() {

 

          return sex;

 

     }

 

     public void setSex(String sex) {

 

          this.sex = sex;

 

     }

 

     public int getUserId() {

 

          return userId;

 

     }

 

     public void setUserId(int userId) {

 

          this.userId = userId;

 

     }

 

     public String getUserName() {

 

          return userName;

 

     }

 

     public void setUserName(String userName) {

 

          this.userName = userName;

 

     }    

 

}

===============================================================

2.1.     没有使用dbutils的数据访问层(只需直连包)

 

首先,创建所有数据访问类的抽象基类BaseDAO

view plaincopy to clipboardprint?

package com.saga.dao;  

import java.sql.Connection;  

import java.sql.DriverManager;  

import java.sql.PreparedStatement; 

import java.sql.ResultSet; 

import java.sql.SQLException; 

/** 

 * 所有数据访问类的基类,其他数据访问类需继承此类 

 *@author saga1320 

*/

public abstract class BaseDAO {   

     //数据库连接驱动名  

     private static final String DRIVERNAME    

="com.microsoft.sqlserver.jdbc.SQLServerDriver";    

     //数据库连接URL    

     private static final String RUL    

="jdbc:sqlserver://localhost:1433;databaseName=stuDB";    

     //数据库用户名    

     private static final String UNAME="sa";    

     //密码    

     private static final String PWD="";    

     private Connection conn=null;    

          

     /**  

      * 建立数据库连接  

      * @throws ClassNotFoundException   

      * @throws SQLException   

      */   

     private void getConnection()     

throws ClassNotFoundException,SQLException{    

          Class.forName(DRIVERNAME);    

          conn=DriverManager.getConnection(RUL,UNAME,PWD);       

     }          

     public BaseDAO() {    

          super();    

     }    

          

     /**  

      * 执行增,删,改,(带参数)  

      * @param strSql sql语句    

      * @param param 参数  

      * @return sql语句所影响的行数  

      * @throws SQLException    

      * @throws ClassNotFoundException   

      */ 

     protected int executeUpdate(String strSql,Object[] param)   

 

throws ClassNotFoundException,SQLException{  

 

          if(conn==null || conn.isClosed()){  

 

                 this.getConnection();  

 

          }  

 

          PreparedStatement pstat=conn.prepareStatement(strSql);  

 

          for (int i = 0; i < param.length; i++) {  

 

                pstat.setObject(i+1,param[i]);  

 

          }  

 

          return pstat.executeUpdate();  

 

     }  

 

     /** 

 

      * 执行增,删,改,(不带参数) 

 

      * @param strSql sql语句 

 

      * @return sql语句所影响的行数 

 

      * @throws SQLException  

 

      * @throws ClassNotFoundException  

 

      */ 

 

     protected int executeUpdate(String strSql)   

 

throws ClassNotFoundException,SQLException{  

 

          if(conn==null || conn.isClosed()){  

 

                 this.getConnection();  

 

          }  

 

          PreparedStatement pstat=conn.prepareStatement(strSql);  

 

          return pstat.executeUpdate();  

 

     }  

 

     /** 

 

      * 带参数查询 

 

      * @param strSql sql语句 

 

      * @param param 参数 

 

      * @return ResultSet 结果集 

 

      * @throws ClassNotFoundException  

 

      * @throws SQLException  

 

      */ 

 

     protected ResultSet executeQuery(String strSql,Object[] param)   

 

throws SQLException,ClassNotFoundException{  

 

          if(conn==null || conn.isClosed()){  

 

                 this.getConnection();  

 

          }  

 

          PreparedStatement pstat=conn.prepareStatement(strSql);  

 

          for (int i = 0; i < param.length; i++) {  

 

                pstat.setObject(i+1,param[i]);  

 

          }  

 

          return pstat.executeQuery();  

 

     }  

 

     /** 

 

      * 无参查询 

 

      * @param strSql sql语句 

 

      * @param param 参数 

 

      * @return ResultSet 结果集 

 

      * @throws SQLException 

 

      * @throws ClassNotFoundException 

 

      */ 

 

     protected ResultSet executeQuery(String strSql)   

 

throws SQLException,ClassNotFoundException{  

 

          if(conn==null || conn.isClosed()){  

 

                 this.getConnection();  

 

          }  

 

          PreparedStatement pstat=conn.prepareStatement(strSql);  

 

          return pstat.executeQuery();  

 

     }  

 

   

 

     /** 

 

      * 关闭数据库连接 

 

      * @throws SQLException 

 

      */ 

     protected void closeConnection() throws SQLException{  

          if(conn!=null){  

                 if(!conn.isClosed()){  

                      conn.close();  

                 }  

          }  

     }  

package com.saga.dao;

 

 

 

import java.sql.Connection;

 

import java.sql.DriverManager;

 

import java.sql.PreparedStatement;

 

import java.sql.ResultSet;

 

import java.sql.SQLException;

 

/**

 

 * 所有数据访问类的基类,其他数据访问类需继承此类

 

 *@author saga1320

 

*/

 

public abstract class BaseDAO {

 

     //数据库连接驱动名

 

     private static final String DRIVERNAME

 

="com.microsoft.sqlserver.jdbc.SQLServerDriver";

 

     //数据库连接URL

 

     private static final String RUL

 

="jdbc:sqlserver://localhost:1433;databaseName=stuDB";

 

     //数据库用户名

 

     private static final String UNAME="sa";

 

     //密码

 

     private static final String PWD="";

 

     private Connection conn=null;

 

     

 

     /**

 

      * 建立数据库连接

 

      * @throws ClassNotFoundException

 

      * @throws SQLException

 

      */

 

     private void getConnection()

 

throws ClassNotFoundException,SQLException{

 

          Class.forName(DRIVERNAME);

 

          conn=DriverManager.getConnection(RUL,UNAME,PWD);  

 

     }

 

 

 

     public BaseDAO() {

 

          super();

 

     }

 

     

 

     /**

 

      * 执行增,删,改,(带参数)

 

      * @param strSql sql语句 

 

      * @param param 参数

 

      * @return sql语句所影响的行数

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     protected int executeUpdate(String strSql,Object[] param)

 

throws ClassNotFoundException,SQLException{

 

          if(conn==null || conn.isClosed()){

 

                 this.getConnection();

 

          }

 

          PreparedStatement pstat=conn.prepareStatement(strSql);

 

          for (int i = 0; i < param.length; i++) {

 

                 pstat.setObject(i+1,param[i]);

 

          }

 

          return pstat.executeUpdate();

 

     }

 

     /**

 

      * 执行增,删,改,(不带参数)

 

      * @param strSql sql语句

 

      * @return sql语句所影响的行数

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     protected int executeUpdate(String strSql)

 

throws ClassNotFoundException,SQLException{

 

          if(conn==null || conn.isClosed()){

 

                 this.getConnection();

 

          }

 

          PreparedStatement pstat=conn.prepareStatement(strSql);

 

          return pstat.executeUpdate();

 

     }

 

     /**

 

      * 带参数查询

 

      * @param strSql sql语句

 

      * @param param 参数

 

      * @return ResultSet 结果集

 

      * @throws ClassNotFoundException

 

      * @throws SQLException

 

      */

 

     protected ResultSet executeQuery(String strSql,Object[] param)

 

throws SQLException,ClassNotFoundException{

 

          if(conn==null || conn.isClosed()){

 

                 this.getConnection();

 

          }

 

          PreparedStatement pstat=conn.prepareStatement(strSql);

 

          for (int i = 0; i < param.length; i++) {

 

                 pstat.setObject(i+1,param[i]);

 

          }

 

          return pstat.executeQuery();

 

     }

 

     /**

 

      * 无参查询

 

      * @param strSql sql语句

 

      * @param param 参数

 

      * @return ResultSet 结果集

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     protected ResultSet executeQuery(String strSql)

 

throws SQLException,ClassNotFoundException{

 

          if(conn==null || conn.isClosed()){

 

                 this.getConnection();

 

          }

 

           PreparedStatementpstat=conn.prepareStatement(strSql);

 

          return pstat.executeQuery();

 

     }

 

 

 

     /**

 

      * 关闭数据库连接

 

      * @throws SQLException

 

      */

     protected void closeConnection() throws SQLException{

          if(conn!=null){

                 if(!conn.isClosed()){

                      conn.close();

                 }

          }

     }

}

 

 

 

 

 

接着,创建USERS表的数据访问类:USersDAO

 

 

 

view plaincopy to clipboardprint?

package com.saga.dao;  

 

   

 

import java.sql.ResultSet;  

 

import java.sql.SQLException;  

 

import java.util.ArrayList;  

 

import java.util.List;  

 

   

 

import com.saga.entity.UsersEntity;  

 

   

 

/** 

 

 *USERS表的数据访问类,继承BaseDAO 

 

 *@author saga1320 

 

*/ 

 

   

 

public class UsersDAO extends BaseDAO{  

 

        

 

     public UsersDAO(){  

 

          super();  

 

     }  

 

        

 

     /** 

 

      * 向USERS表中添加一条数据 

 

      * @param user UsersEntity封装了数据信息 

 

      * @return int 添加记录的行数 

 

      * @throws SQLException 

 

      * @throws ClassNotFoundException 

 

      */ 

 

     public int insertUser(UsersEntity user)   

 

throws ClassNotFoundException,SQLException{  

 

          int = 0;  

 

          String strSql="INSERT INTO USERS VALUES(?,?,?,?)";  

 

          Object [] param = new Object [] {  

 

                 user.getUserName(),  

 

                 user.getPassword(),  

 

                 user.getRealName(),  

 

                user.getSex()  

 

          };  

 

          i = super.executeUpdate(strSql, param);  

 

          super.closeConnection();  

 

          return i;  

 

     }  

 

        

 

   /** 

 

      * 根据userId修改USERS信息 

 

       * @param user UsersEntity封装了数据信息 

 

      * @return int 修改记录的行数 

 

      * @throws SQLException 

 

      * @throws ClassNotFoundException 

 

      */ 

 

     public int updateUsersById(UsersEntity user)   

 

throws ClassNotFoundException, SQLException{  

 

          int = 0;  

 

          String strSql="UPDATE USERS SET userName=?, password=?, realName=?,sex=? WHEREuserId=?";  

 

          Object [] param = new Object [] {  

 

                 user.getUserName(),  

 

                user.getPassword(),  

 

                 user.getRealName(),  

 

                 user.getSex(),  

 

                 user.getUserId()  

 

          };  

 

          i = super.executeUpdate(strSql, param);  

 

          super.closeConnection();  

 

          return i;  

 

     }  

 

   

 

      /** 

 

      * 查询USERS表的所有信息 

 

      * @return List<UsersEntity> UsersEntity实体的泛型集合 

 

      * @throws SQLException 

 

      * @throws ClassNotFoundException 

 

      */ 

 

     public List<UsersEntity> getAllUsers()   

 

throws SQLException,ClassNotFoundException{  

 

          List<UsersEntity> listUsers = newArrayList<UsersEntity>();  

 

          String strSql="SELECT * FROM USERS";  

 

          ResultSet rs=this.executeQuery(strSql);  

 

          while(rs.next()){  

 

                 UsersEntity user=newUsersEntity();  

 

                user.setUserId(rs.getInt("userId"));  

 

                 user.setUserName(rs.getString("userName"));  

 

                user.setPassword(rs.getString("password"));  

 

                user.setRealName(rs.getString("RealName"));  

 

                user.setSex(rs.getString("sex"));  

 

                 listUsers.add(user);  

 

          }  

 

          super.closeConnection();  

 

          return listUsers;  

 

     }  

 

        

 

      /** 

 

      * 根据userId查询USERS表信息 

 

      * @return UsersEntity 

 

      * @throws SQLException 

 

      * @throws ClassNotFoundException 

 

      */ 

 

     public UsersEntity getUserById(String userId)   

 

throws SQLException,ClassNotFoundException{  

 

          UsersEntity User = null;  

 

          String strSql="SELECT * FROM USERS WHERE userId=?";  

 

          ResultSet rs=this.executeQuery(strSql, new Object [] {userId});  

 

          if(rs.next()){  

 

                 user=new UsersEntity();  

 

                user.setUserId(rs.getInt("userId"));  

 

                user.setUserName(rs.getString("userName"));  

 

                user.setPassword(rs.getString("password"));  

 

                user.setRealName(rs.getString("RealName"));  

 

                user.setSex(rs.getString("sex"));  

  

          }  

 

          super.closeConnection();  

 

          return User;  

 

     }  

 

package com.saga.dao;

 

 

 

import java.sql.ResultSet;

 

import java.sql.SQLException;

 

import java.util.ArrayList;

 

import java.util.List;

 

 

 

import com.saga.entity.UsersEntity;

 

 

 

/**

 

 *USERS表的数据访问类,继承BaseDAO

 

 *@author saga1320

 

*/

 

 

 

public class UsersDAO extends BaseDAO {

 

     

 

     public UsersDAO(){

 

          super();

 

     }

 

     

 

     /**

 

      * 向USERS表中添加一条数据

 

      * @param user UsersEntity封装了数据信息

 

      * @return int 添加记录的行数

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     public int insertUser(UsersEntity user)

 

throws ClassNotFoundException,SQLException{

 

          int = 0;

 

          String strSql="INSERT INTO USERS VALUES(?,?,?,?)";

 

          Object [] param = new Object [] {

 

                 user.getUserName(),

 

                 user.getPassword(),

 

                 user.getRealName(),

 

                 user.getSex()

 

          };

 

          i = super.executeUpdate(strSql, param);

 

          super.closeConnection();

 

          return i;

 

     }

 

     

 

   /**

 

      * 根据userId修改USERS信息

 

      * @param user UsersEntity封装了数据信息

 

       * @return int 修改记录的行数

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     public int updateUsersById(UsersEntity user)

 

throws ClassNotFoundException,SQLException{

 

          int = 0;

 

          String strSql="UPDATE USERS SET userName=?, password=?, realName=?,sex=? WHERE userId=?";

 

          Object [] param = new Object [] {

 

                 user.getUserName(),

 

                 user.getPassword(),

 

                 user.getRealName(),

 

                 user.getSex(),

 

                 user.getUserId()

 

          };

 

          i = super.executeUpdate(strSql, param);

 

          super.closeConnection();

 

          return i;

 

     }

 

 

 

      /**

 

      * 查询USERS表的所有信息

 

      * @return List<UsersEntity> UsersEntity实体的泛型集合

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     public List<UsersEntity> getAllUsers()

 

throws SQLException,ClassNotFoundException{

 

          List<UsersEntity> listUsers = new ArrayList<UsersEntity>();

 

          String strSql="SELECT * FROM USERS";

 

          ResultSet rs=this.executeQuery(strSql);

 

          while(rs.next()){

 

                 UsersEntity user=newUsersEntity();

 

                user.setUserId(rs.getInt("userId"));

 

                user.setUserName(rs.getString("userName"));

 

                user.setPassword(rs.getString("password"));

 

                user.setRealName(rs.getString("RealName"));

 

                 user.setSex(rs.getString("sex"));

 

                 listUsers.add(user);

 

          }

 

          super.closeConnection();

 

          return listUsers;

 

     }

 

     

 

      /**

 

      * 根据userId查询USERS表信息

 

      * @return UsersEntity

 

      * @throws SQLException

 

      * @throws ClassNotFoundException

 

      */

 

     public UsersEntity getUserById(String userId)

 

throws SQLException,ClassNotFoundException{

 

          UsersEntity User = null;

 

          String strSql="SELECT * FROM USERS WHERE userId=?";

 

          ResultSet rs=this.executeQuery(strSql, new Object [] {userId});

 

          if(rs.next()){

 

                 user=new UsersEntity();

 

                user.setUserId(rs.getInt("userId"));

 

                 user.setUserName(rs.getString("userName"));

 

                user.setPassword(rs.getString("password"));

 

                user.setRealName(rs.getString("RealName"));

 

                user.setSex(rs.getString("sex"));

 

          }

 

          super.closeConnection();

 

          return User;

 

     }

 

}

 

 

 

最后,只需要在业务层调用这些方法就行了。

 

 

==============================================================================================================================================================

2.2.     使用dbutils的数据访问层(需直连包,dbutils包)

 

首先,创建所有数据访问类的抽象基类BaseDAO

view plaincopy to clipboardprint?

package com.saga.dao;  

import java.sql.Connection;  

import java.sql.DriverManager;  

import java.sql.SQLException;    

import java.util.List;    

importorg.apache.commons.dbutils.DbUtils;    

importorg.apache.commons.dbutils.QueryRunner;    

importorg.apache.commons.dbutils.ResultSetHandler;  

 

    

public abstract class BaseDAO {    

     private static final String DRIVERNAME     

="com.microsoft.sqlserver.jdbc.SQLServerDriver";    

     private static final String URL     

="jdbc:sqlserver://localhost:1433;databaseName=stuDB";    

     private static final String UID = "sa";    

     private static final String PWD = "";    

     private Connection conn = null;               

     public BaseDAO() {    

          super();    

     }             

------------------------------------------------------------------------------------------------ 

     /** 

 

      *  建立数据库连接  

      * @throws SQLException  

      */ 

     private void getConnection() throws SQLException{    

          DbUtils.loadDriver(DRIVERNAME);    

          conn = DriverManager.getConnection(URL,UID,PWD);    

     }    

     /**  

      *  关闭数据库连接  

      * @throws SQLException  

      */   

     protected void closeConnection() throws SQLException{    

          DbUtils.close(conn);  

     }    

=================================================

     /** 

 

      * 带参数的查询 

      * @param strSql 查询语句 

      * @param param 参数 

      * @param rsh ResultSetHandler接口的实现对象 

      * @return 查询结果的集合 

      * @throws SQLException 

      */ 

     protected List executeQuery(String strSql, Object[] param,ResultSetHandler rsh) throws SQLException{  

          if (conn == null || conn.isClosed()) {  

                 this.getConnection();  

          }  

          QueryRunner runner = new QueryRunner();  

          return (List) runner.query(conn, strSql, param, rsh);  

     }  

        

     /** 

 

      * 不带参数的查询 

      * @param strSql 查询语句 

      * @param rsh ResultSetHandler接口的实现对象 

      * @return 查询结果的集合 

      * @throws SQLException 

      */ 

     protected List executeQuery(String strSql, ResultSetHandler rsh) throwsSQLException{  

          if (conn == null || conn.isClosed()) {  

                 this.getConnection();  

          }  

          QueryRunner runner = new QueryRunner();  

          return (List) runner.query(conn, strSql, rsh);  

     }  

     /** 

      * 查询一条记录 

      * @param strSql 查询语句 

      * @param param 参数 

      * @param rsh ResultSetHandler接口的实现对象 

      * @return 记录对应的实体 

      * @throws SQLException 

      */ 

     protected Object executeQueryObject(String strSql, Object[] param,ResultSetHandler rsh) throws SQLException{  

          if (conn == null || conn.isClosed()) {  

                this.getConnection();  

          }  

          QueryRunner runner = new QueryRunner();  

          return  runner.query(conn, strSql,param, rsh);  

      }  

     /** 

      * 带参数的增,删,改 

      * @param strSql 增,删,改的执行语句 

      * @param param 参数 

      * @return 影响的记录数 

      * @throws SQLException 

      */ 

     protected int executeUpdate(String strSql, Object[] param) throwsSQLException{  

          if (conn == null || conn.isClosed()) {  

                 this.getConnection();  

          }  

          QueryRunner runner = new QueryRunner();  

          return runner.update(conn, strSql, param);  

     }  

        

     /** 

      * 不带参数的增,删,改 

      * @param strSql 增,删,改的执行语句 

      * @return 影响的记录数 

      * @throws SQLException 

      */ 

     protected int executeUpdate(String strSql) throws SQLException{  

          if (conn == null || conn.isClosed()) {  

                 this.getConnection();  

          }   

          QueryRunner runner = new QueryRunner();  

          return runner.update(conn, strSql);  

     }  

 

 

package com.saga.dao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.util.List;

import org.apache.commons.dbutils.DbUtils;

importorg.apache.commons.dbutils.QueryRunner;

importorg.apache.commons.dbutils.ResultSetHandler;

public abstract class BaseDAO {

     private static final String DRIVERNAME

= "com.microsoft.sqlserver.jdbc.SQLServerDriver";

     private static final String URL

="jdbc:sqlserver://localhost:1433;databaseName=stuDB";

     private static final String UID = "sa";

     private static final String PWD = "";

     private Connection conn = null;

     public BaseDAO() {

          super();

     }

     

 

     /**

 

      *  建立数据库连接

      * @throws SQLException

      */

     private void getConnection() throws SQLException{

 

          DbUtils.loadDriver(DRIVERNAME);

 

          conn = DriverManager.getConnection(URL,UID,PWD);

 

     }

 

     

 

     /**

 

      *  关闭数据库连接

 

      * @throws SQLException

 

      */

 

     protected void closeConnection() throws SQLException{

 

          DbUtils.close(conn);

 

     }

 

 

 

     /**

 

      * 带参数的查询

 

      * @param strSql 查询语句

 

      * @param param 参数

 

      * @param rsh ResultSetHandler接口的实现对象

 

      * @return 查询结果的集合

 

      * @throws SQLException

 

      */

 

     protected List executeQuery(String strSql, Object[] param,ResultSetHandler rsh) throws SQLException{

 

          if (conn == null || conn.isClosed()) {

 

                 this.getConnection();

 

          }

 

          QueryRunner runner = new QueryRunner();

 

          return (List) runner.query(conn, strSql, param, rsh);

 

     }

 

     

 

     /**

 

      * 不带参数的查询

 

      * @param strSql 查询语句

 

      * @param rsh ResultSetHandler接口的实现对象

 

      * @return 查询结果的集合

 

      * @throws SQLException

 

      */

 

     protected List executeQuery(String strSql, ResultSetHandler rsh) throwsSQLException{

 

          if (conn == null || conn.isClosed()) {

 

                 this.getConnection();

 

          }

 

          QueryRunner runner = new QueryRunner();

 

          return (List) runner.query(conn, strSql, rsh);

 

     }

 

     

 

     /**

 

      * 查询一条记录

 

      * @param strSql 查询语句

 

      * @param param 参数

 

      * @param rsh ResultSetHandler接口的实现对象

 

      * @return 记录对应的实体

 

      * @throws SQLException

 

      */

 

     protected Object executeQueryObject(String strSql, Object[] param,ResultSetHandler rsh) throws SQLException{

 

          if (conn == null || conn.isClosed()) {

 

                 this.getConnection();

 

          }

 

          QueryRunner runner = new QueryRunner();

 

          return  runner.query(conn, strSql,param, rsh);

 

     }

 

     

 

     /**

 

      * 带参数的增,删,改

 

      * @param strSql 增,删,改的执行语句

 

      * @param param 参数

 

      * @return 影响的记录数

 

      * @throws SQLException

 

      */

 

     protected int executeUpdate(String strSql, Object[] param) throwsSQLException{

 

          if (conn == null || conn.isClosed()) {

 

                 this.getConnection();

 

          }

 

          QueryRunner runner = new QueryRunner();

 

          return runner.update(conn, strSql, param);

 

     }

 

     

 

     /**

 

      * 不带参数的增,删,改

 

      * @param strSql 增,删,改的执行语句

 

      * @return 影响的记录数

 

      * @throws SQLException

 

      */

 

     protected int executeUpdate(String strSql) throws SQLException{

 

          if (conn == null || conn.isClosed()) {

 

                 this.getConnection();

 

          }

 

          QueryRunner runner = new QueryRunner();

 

          return runner.update(conn, strSql);

 

     }

 

}

 

 

 

 

接着,创建USERS表的数据访问类:USersDAO

 

 

view plaincopy to clipboardprint?

package com.saga.dao;  

 

   

 

import java.sql.SQLException;  

 

import java.util.List;  

 

   

 

importorg.apache.commons.dbutils.ResultSetHandler;  

 

importorg.apache.commons.dbutils.handlers.BeanHandler;  

 

importorg.apache.commons.dbutils.handlers.BeanListHandler;  

 

   

 

import com.saga.entity.UsersEntity;  

 

   

 

public class UsersDAO extends BaseDAO{  

 

   

 

     public UsersDAO() {  

 

          super();  

 

          // TODO Auto-generated constructor stub  

 

     }  

 

        

 

     /** 

 

      * 得到USERS表所有的记录 

 

      * @return List UserEntity的集合 

 

      * @throws SQLException 

 

      */ 

 

     public List getAllUsers() throws SQLException{  

 

          List listUsers = null;  

 

          String strSql = "SELECT * FROM USERS";  

 

          ResultSetHandler rsh = new BeanListHandler(UsersEntity.class);  

 

          listUsers = super.executeQuery(strSql, rsh);  

 

          super.closeConnection();  

 

          return listUsers;  

 

     }  

 

        

 

     /** 

 

      * 根据USERS编号得到USERS信息 

 

      * @param userId USERS编号 

 

      * @return UsersEntity 

 

      * @throws SQLException 

 

      */ 

 

     public UsersEntity getUsersById(String userId) throws SQLException{  

 

          UsersEntity user = null;  

 

           String strSql = "SELECT * FROMUSERS WHERE userId = ?";  

 

          ResultSetHandler rsh = new BeanHandler(UsersEntity.class);  

 

          user = (UsersEntity) super.executeQueryObject(strSql, new Object[]{userId}, rsh);  

 

          super.closeConnection();  

 

          return user;  

 

     }  

 

        

 

     /** 

 

      * 向USERS表添加一条记录 

 

      * @param user UsersEntity对象 

 

      * @return int 

 

      * @throws SQLException 

 

      */ 

 

      public int insertUser(UsersEntity user)throws SQLException{  

 

          int i = 0;  

 

          String strSql = "INSERT INTO USERS VALUES(?,?,?,?)";  

 

          Object [] param = new Object [] {  

 

                      user.getUserName(),  

 

                      user.getPassword(),  

 

                      user.getRealName(),  

 

                      user.getSex()  

 

          };  

 

          i = super.executeUpdate(strSql, param);  

 

          super.closeConnection();  

 

          return i;  

 

     }  

 

        

 

     /** 

 

      * 根据USERS编号修改USERS信息 

 

      * @param user UsersEntity对象 

 

      * @return int 

 

      * @throws SQLException 

 

      */ 

 

      public int updateUserById(UsersEntityuser) throws SQLException{  

 

          int i = 0;  

 

          String strSql = "UPDATE USERS SET userName=?, password=?,realName=?, sex=? WHEREuserId=?";  

 

          Object [] param = new Object [] {  

 

                      user.getUserName(),  

 

                      user.getPassword(),  

 

                      user.getRealName(),  

 

                      user.getSex(),  

 

                      user.getUserId()  

 

          };   

 

          i = super.executeUpdate(strSql, param);  

 

          super.closeConnection();  

 

          return i;  

 

     }  

 

package com.saga.dao;

 

 

 

import java.sql.SQLException;

 

import java.util.List;

 

 

 

import org.apache.commons.dbutils.ResultSetHandler;

 

importorg.apache.commons.dbutils.handlers.BeanHandler;

 

importorg.apache.commons.dbutils.handlers.BeanListHandler;

 

 

 

import com.saga.entity.UsersEntity;

 

 

 

public class UsersDAO extends BaseDAO {

 

 

 

     public UsersDAO() {

 

          super();

 

          // TODO Auto-generated constructor stub

 

     }

 

     

 

     /**

 

      * 得到USERS表所有的记录

 

      * @return List UserEntity的集合

 

      * @throws SQLException

 

      */

 

     public List getAllUsers() throws SQLException{

 

          List listUsers = null;

 

          String strSql = "SELECT * FROM USERS";

 

          ResultSetHandler rsh = new BeanListHandler(UsersEntity.class);

 

          listUsers = super.executeQuery(strSql, rsh);

 

          super.closeConnection();

 

          return listUsers;

 

     }

 

     

 

     /**

 

      * 根据USERS编号得到USERS信息

 

      * @param userId USERS编号

 

      * @return UsersEntity

 

      * @throws SQLException

 

      */

 

     public UsersEntity getUsersById(String userId) throws SQLException{

 

          UsersEntity user = null;

 

          String strSql = "SELECT * FROM USERS WHERE userId = ?";

 

          ResultSetHandler rsh = new BeanHandler(UsersEntity.class);

 

           user = (UsersEntity)super.executeQueryObject(strSql, new Object []{userId}, rsh);

 

          super.closeConnection();

 

          return user;

 

     }

 

     

 

     /**

 

      * 向USERS表添加一条记录

 

      * @param user UsersEntity对象

 

      * @return int

 

      * @throws SQLException

 

      */

 

     public int insertUser(UsersEntity user) throws SQLException{

 

          int i = 0;

 

          String strSql = "INSERT INTO USERS VALUES(?,?,?,?)";

 

          Object [] param = new Object [] {

 

                      user.getUserName(),

 

                      user.getPassword(),

 

                      user.getRealName(),

 

                      user.getSex()

 

          };

 

          i = super.executeUpdate(strSql, param);

 

          super.closeConnection();

 

          return i;

 

     }

 

     

 

     /**

 

      * 根据USERS编号修改USERS信息

 

      * @param user UsersEntity对象

 

      * @return int

 

      * @throws SQLException

 

      */

 

     public int updateUserById(UsersEntity user) throws SQLException{

 

          int i = 0;

 

          String strSql = "UPDATE USERS SET userName=?, password=?,realName=?, sex=? WHERE userId=?";

 

          Object [] param = new Object [] {

 

                     user.getUserName(),

 

                      user.getPassword(),

 

                      user.getRealName(),

 

                      user.getSex(),

 

                      user.getUserId()

 

          };

 

          i = super.executeUpdate(strSql, param);

 

          super.closeConnection();

 

          return i;

 

     }

 

}

 

 

 

 

 

最后,只需要在业务层调用这些方法就行了。

 

但是,如果使用dbutils包的话,需要注意以下几点:

 

a、实体类属性的名称要与库中字段的名字一致,否则无法查到结果。

 

b、ResultSetHandler rsh = 接口的实现类

 

如果返回对象的话使用newBeanHandler();

 

     如果返回的是集合的话使用 newBeanListHandler();   

 

 

 

这里只介绍了dbutils的一种基本用法,至于dbutils的其他用法,有兴趣的朋友可以参考一下dbutils帮助文档。

 

 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/saga1320/archive/2008/11/09/3257994.aspx

posted @ 2013-06-08 21:36  廖世勇  阅读(312)  评论(0编辑  收藏  举报