ITeye博客

JDBC CRUD操作的粗略封装DEMO

BestUpon · 2009-10-15 12:19 · J2EE · 企业架构 · Markdown

暮然回首,看看jDBC的操作,原来很多的东西都忘记了,数据库的的语句也忘得差不多了,还的捡起来以前的东西,自己粗糙的写了一个封装JDBC的CURD的方法,回顾回顾以前的东西。

类名:BasedDaoSupport。主要功能为Dao提供一次分装的接口。

注:有几个类是工具类,获得JDBC的链接和独缺配置文件的。

package cn.edu.lzcc.orderdishes.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import cn.edu.lzcc.orderdishes.exception.ObejectIdException;
/**
 * 
 * Project: orderdishes
 * Package: cn.edu.lzcc.orderdishes.utils
 * @author  bestupon
 * Email:   bestupon@foxmail.com
 * DateTime:Oct 15, 2009 2:06:59 AM
 * JDBC的数据封装类
 * 实现了增删改查的基本操作。
 */

public class BaseDaoSupport {
	private boolean result=false;
	Connection conn = DataBaseConnection.getConnection();
	Statement stmt = DataBaseConnection.createStatement(conn);
	ResultSet rs = null;
	/**
	 * 插入增加的方法
	 * @param entityTable 要操作的表的名称
	 * @param propertys 操作的表的属性名称
	 * @param params 增加的值
	 * @return 成功与否
	 * @throws SQLException
	 */
	public  boolean  addObject(String entityTable,String []propertys,Object[]params) throws SQLException {
		StringBuffer insertSql =new StringBuffer("");
		if(null !=entityTable &&!entityTable.equals("")) {
			insertSql.append("INSERT INTO  ");
		}else {
			return result;
		}
		if(null !=propertys && propertys.length >=1) {
			insertSql.append(entityTable.toLowerCase());
			insertSql.append("  (");
			 for(int i= 0 ; i<propertys.length;i++) {
				 insertSql.append(propertys[i]);
				 insertSql.append(",");
				 if(propertys[i].trim().toLowerCase().equals(entityTable.toLowerCase()+"id") && propertys[i]!=null) {
					 ObejectIdException oie =  new ObejectIdException("增加方法中的ObjectId的值必须是‘null’值causeby:(主键不能有重复值)");
					 throw oie;
				 }
			 }
			 insertSql = new StringBuffer(insertSql.substring(0, insertSql.length()-1));
			 insertSql.append(" )");
		}
		if(null !=params) {
			insertSql.append(" VALUES (");
			 for(int i= 0 ; i<propertys.length;i++) {
				 if(params[i] != null) {
					 insertSql.append("'").append(params[i]).append("',");
				 }else {
					 insertSql.append(params[i]).append(",");
				 }
			 }
			 insertSql = new StringBuffer(insertSql.substring(0, insertSql.length()-1));
			 insertSql.append(" ) ;");
		}
		System.out.println(insertSql.toString());
		result =DataBaseConnection.executeUpdate(conn, insertSql.toString())>0 ? true :false;
		return result;
	}
	/**
	 * 删除操作
	 * @param entityTable
	 * @param objectId
	 * @return
	 * @throws SQLException
	 */
	public  boolean  delObject(String entityTable,String sqlWhere) throws SQLException {
		StringBuffer deleteSql = new StringBuffer(""); 
		deleteSql.append("DELETE FROM  ");
		deleteSql.append(entityTable.toLowerCase());
		if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {
			if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){
				deleteSql.append(sqlWhere);
			}else {
				deleteSql.append(" WHERE " ).append(sqlWhere);
			}
		}
		System.out.println(deleteSql.toString());
		result =DataBaseConnection.executeUpdate(conn, deleteSql.toString())>0 ? true :false;
		return result;
	}
	/**
	 * 更新修改的方法
	 * @param entityTable 实体表名称
	 * @param propertys 更新的字段名称
	 * @param params 更新的值
	 * @param sqlWhere 条件语句
	 * @return 返回成功与否
	 * @throws SQLException
	 */
	public  boolean  modifyObject(String entityTable,String []propertys,Object[]params,String sqlWhere) throws SQLException {
		StringBuffer updateSql =new StringBuffer("");
		if(null !=entityTable &&!entityTable.equals("")) {
			updateSql.append("UPDATE ").append(entityTable.toLowerCase());
		}else {
			return result;
		}
		if(null !=propertys ) {
			if(null !=params) {
				if(propertys.length == params.length) {
					for(int i= 0 ; i<propertys.length;i++) {
						updateSql.append("  SET ");
						updateSql.append(propertys[i]).append("=").append("'").append(params[i]).append("',");
						 if(propertys[i].trim().toLowerCase().equals(entityTable.toLowerCase()+"id")) {
							 ObejectIdException oie =  new ObejectIdException("修改方法中的ObjectId的值不能被更新causeBy(主键唯一性)");
							 throw oie;
						 }
					}
					
					updateSql = new StringBuffer(updateSql.substring(0, updateSql.length()-1));
					
					if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {
						if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){
							updateSql.append(sqlWhere);
						}else {
							updateSql.append(" WHERE " ).append(sqlWhere);
						}
					}
				}else{
					return result;
				}
			}
		}
		result =DataBaseConnection.executeUpdate(conn, updateSql.toString())>0 ? true :false;
		System.out.println(updateSql.toString());
		return result;
	}
	
	/**
	 * 查询方法
	 * @param entityTable 要操作的表的名称
	 * @param propertys 表中所还有的属性,字段的名称,也就是主要关心的字段的名称
	 * @param sqlWhere 是附加的查询条件,可以含有where 关键字,也可以不含有where关键字均可
	 * @return 查到的ResultSet结果集
	 * @throws SQLException
	 */
	public  ResultSet  queryObject(String entityTable,Object []propertys,String sqlWhere) throws SQLException {
		StringBuffer querySql = new StringBuffer("");
		if(null !=entityTable &&!entityTable.equals("") &&(null == propertys ||propertys.length<1)) {
			querySql.append("SELECT * FROM ").append(entityTable.toLowerCase());
		}else if(null !=entityTable &&!entityTable.equals("") &&(null != propertys ||propertys.length>=1)) {
			if(null !=propertys && propertys.length >=1) {
				querySql.append("SELECT  ");
				 for(int i= 0 ; i<propertys.length;i++) {
					 querySql.append(propertys[i]).append(",");
				 }
				 querySql = new StringBuffer(querySql.substring(0, querySql.length()-1));
			}
			querySql.append(" FROM ").append(entityTable.toLowerCase());
		}
		if(null != sqlWhere && !sqlWhere.equals("") &&sqlWhere.length()>1) {
			if(sqlWhere.trim().split(" ")[0].toLowerCase().equals("where")){
				querySql.append(sqlWhere);
			}else {
				querySql.append(" WHERE " ).append(sqlWhere);
			}
		}
		System.out.println(querySql);
		rs = DataBaseConnection.executeQuery(stmt, querySql.toString());
		return rs ;
	}
}

 

定义一个Dao接口。如下

package cn.edu.lzcc.orderdishes.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface FareMenuDao {
	/**
	 * 增加
	 * @return
	 */
	public boolean addFareMenu(String entityTable,String []propertys,Object[]params) throws SQLException ;
	/**
	 * 修改
	 * @param fareMenuId
	 * @return
	 */
	public boolean modifyFareMenu(String entityTable,String []propertys,Object[]params,String sqlWhere) throws SQLException ;
	/**
	 * 删除
	 * @param fareMenuId
	 * @return
	 */
	public boolean delFareMenu(String entityTable,String sqlWhere) throws SQLException ;
	/**
	 * 
	 * @return
	 */
	public ResultSet queryFareMenu(String entityTable, String []propertys, String sqlWhere) throws SQLException;
}

 

一个Dao的实现如此简单。

package cn.edu.lzcc.orderdishes.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import cn.edu.lzcc.orderdishes.dao.FareMenuDao;
import cn.edu.lzcc.orderdishes.utils.BaseDaoSupport;

public class FareMenuImpl extends BaseDaoSupport implements FareMenuDao {

	public boolean addFareMenu(String entityTable,String []propertys,
			Object[] params) throws SQLException {
		return super.addObject(entityTable, propertys, params);
	}

	public boolean delFareMenu(String entityTable, String sqlWhere) throws SQLException {
		return super.delObject(entityTable, sqlWhere);
	}

	public boolean modifyFareMenu(String entityTable, String []propertys,
			Object[] params,String sqlWhere) throws SQLException {
		return super.modifyObject(entityTable, propertys, params,sqlWhere);
	}

	public ResultSet queryFareMenu(String entityTable, String []propertys, String sqlWhere) throws SQLException {
		return super.queryObject(entityTable, propertys, sqlWhere);
	}
}

 

 

附件:能直接运行的源码文件,含有测试文件

评论(9)

  1. #9 楼 · xsjleilei · 2013-05-23 10:41

    基本没有啥用,可以作为入门示例。

  2. #8 楼 · BestUpon · 2010-07-11 15:28

    shouzhang1_2 writes:

    写的可以 请问 楼主 在DataBaseConnection类中,executeQuery方法的conn在哪里释放的?

    写的严格一点的话,应该每一次操作都要有关闭操作,这个程序和了好久了,也写的很粗糙,估计你没有看见关闭方法的话,就加一个final{close(...)};

  3. #7 楼 · shouzhang1_2 · 2010-07-10 15:12

    写的可以 请问 楼主 在DataBaseConnection类中,executeQuery方法的conn在哪里释放的?

  4. #6 楼 · shouzhang1_2 · 2010-07-06 16:44

    写的确实不错, :idea:

  5. #5 楼 · BestUpon · 2009-10-16 17:27

    回复:4 楼 corejava5 编程最重要的规范,没有一个良好的约定,名称都是乱起的,后来谁也不认识谁了!对于主键我采用的是自动递增形式的,名称采用的是“类名称Id“的形式。这样方便后面的数据库中的操作,要不都叫id,谁能区别是谁的id呢?每个人有自己不同的风格,你的风格不能强加到我的头上吧!所以不要妄自的评论”汗“!

  6. #4 楼 · corejava5 · 2009-10-16 16:58

    你这个貌似对主键字段名或者主键名有限制吧,还有,不能给主键赋值,汗…………

  7. #3 楼 · BestUpon · 2009-10-16 14:05

    勘误:在修改方法中出现一个书写错误,今天才发现的,应该将 updateSql.append(" SET "); ,这句代码放到for循环的外面,源代码中也有错,希望有下载参考的朋友更正下!

  8. #2 楼 · BestUpon · 2009-10-16 14:01

    回复"1 楼 greatghoul“问题: 关闭这些问题都封装在了DataBaseConnection这个工具类中了。每一个方法使用的完成时候都会去关闭statement等。详细信息参见DataBaseConnection工具类。

  9. #1 楼 · greatghoul · 2009-10-16 09:22

    这个倒是有点意思.不过这里有没有提供关闭你在里面用到的 Connection, Statement, ResultSet的方法.这样是个问题.

评论功能维护中,当前仅展示历史评论。