JDBC高级工具类

package dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/** 支持事务处理的数据访问层辅助类 */
public class BaseDao {
	
	private static String DRIVER ;
	private static String URL ;
	private static String USER ;
	private static String PASSWORD ;
	
	static {
		// 使用IO读取属性文件
		InputStream stream = BaseDao.class.getClassLoader().getResourceAsStream("database.properties");
		Properties pro = new Properties();
		try {
			pro.load(stream);
			DRIVER = pro.getProperty("driver");
			URL = pro.getProperty("url");
			USER = pro.getProperty("user");
			PASSWORD = pro.getProperty("password");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 共享预处理命令对象
	private static PreparedStatement psta = null;
	private static Connection con=null;

	/** 获取连接&返回连接对象 */
	public static Connection getConnection() throws ClassNotFoundException, SQLException {		
		Class.forName(DRIVER); // 加载驱动类到内存(反射机制)		
		con = DriverManager.getConnection(URL, USER, PASSWORD); // 获取连接		
		return con; // 返回连接
	}
	
	/**
	 * 开启事务
	 * @return
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public static Connection startTransaction() throws SQLException, ClassNotFoundException {	
		Connection con = getConnection(); // 获取连接		
		con.setAutoCommit(false); // 修改提交方式
		return con;
	}
	
	/**
	 * 关闭(释放)事务
	 * @param con
	 */
	public static void endTransaction(Connection con) {
		try {			
			con.setAutoCommit(true); // 还原事务的默认提交方式			
			BaseDao.closeConnection(con); // 关闭连接释放资源
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 执行增、删、改操作
	 * 
	 * @param 连接对象
	 * @param sql语句
	 * @param 全部参数
	 * @return 返回影响数据库的行数
	 * @throws SQLException
	 */
	public static int dealWithData(Connection con, String sql, /* 设置动态参数 */Object... param) throws SQLException {		
		int num = 0; // 将初始的受影响行数设为0		
		PreparedStatement psta = con.prepareStatement(sql); // 返回预处理命令对象
		if (param != null) {
			for (int i = 0; i < param.length; i++) {
				Object temp = param[i];
				if (temp != null) {
					// 避免SQL注入和脚本攻击
//					temp = param[i].toString().replace("<", "《").replace(">", "》").replace("'", "‘").replace("--", "—")
//							.replace("#", "#");
					temp = param[i].toString().replace("<", "‹").replace(">", "›").replace("--", "—").replace("#", "#");
				}				
				psta.setObject(i + 1, temp); // 替换SQL语句中的 ? 占位符
			}
		}		
		num = psta.executeUpdate(); // 执行sql语句,返回数据库中表的受影响行数
		
		// 判断预处理命令对象是否存在
		if (psta != null) {			
			psta.close(); // 释放预处理命令对象
		}		
		return num; // 返回数据库中表的受影响行数
	}
	
	/**
	 * 使用事务处理数据
	 * @param con
	 * @param sql
	 * @param param
	 * @return
	 * @throws SQLException
	 */
	public static int dealWithDataTransaction(Connection con,String sql,Object... param) throws SQLException {
		int num=0;
		PreparedStatement ps = con.prepareStatement(sql);
		if (null!=param) {
			for (int i = 0; i < param.length; i++) {
				Object temp= param[i];
				if (null!=temp) {
					// 避免SQL注入和脚本攻击
					temp=temp.toString().replace("<", "‹").replace(">", "›").replace("--", "—").replace("#", "#");
				}
				ps.setObject(i+1, temp);  // 替换SQL语句中的 ? 占位符
			}
		}
		// 执行SQL命令,返回影响数据库的行数并赋值
		num=ps.executeUpdate();
		if (null!=ps) {
			ps.close();
		}
		return num;
	}

	/**
	 * 执行查询操作
	 * 
	 * @param 连接对象
	 * @param sql语句
	 * @param 全部参数
	 * @return 返回 ResultSet 只进只读结果集
	 * @throws SQLException
	 */
	public static ResultSet getData(Connection con, String sql, Object... param) throws SQLException {		
		psta = con.prepareStatement(sql); // 返回预处理命令对象
		if (param != null) {
			for (int i = 0; i < param.length; i++) {
				Object temp = param[i];
				if (temp != null) {
					temp = param[i].toString().replace("<", "《").replace(">", "》").replace("'", "‘").replace("--", "—")
							.replace("#", "#");
				}				
				psta.setObject(i + 1, temp); // 从1开始设置参数和对应的值(替换SQL语句中的 ? 占位符)
			}
		}		
		ResultSet rs = psta.executeQuery(); // 执行查询并返回结果集		
		return rs; // 返回数据库中表的受影响行数
	}
	
	/**
	 * 使用事务获取数据
	 * @param con
	 * @param sql
	 * @param param
	 * @return
	 * @throws SQLException
	 */
	public static ResultSet getDataTransaction(Connection con,String sql,Object... param) throws SQLException {
		psta=con.prepareStatement(sql);
		if (null != param) {
			for (int i = 0; i < param.length; i++) {
				Object temp = param[i];
				if (null != temp) {
					// 避免SQL注入和脚本攻击
					temp = temp.toString().replace("<", "‹").replace(">", "›").replace("--", "—").replace("#", "#");
				}				
				psta.setObject(i+1, temp); // 替换SQL语句中的 ? 占位符
			}
		}
		ResultSet rs = psta.executeQuery();
		return rs;
	}

	/** 关闭连接对象 */
	public static void closeConnection(Connection con) {
		try {			 
			if (con != null && !con.isClosed()) { // 检测到连接对象尚未关闭时			
				con.close(); // 关闭连接对象
			}
		} catch (Exception e) {
			System.out.println("\n提示:系统在关闭连接对象时出现异常!");
		}
	}

	/** 关闭预处理命令、连接对象、结果集的连接和释放占用的资源 */
	public static void closeAll(ResultSet rs, Connection con) {
		try {
			if (psta != null) {				
				psta.close(); // 关闭预处理命令对象
			}
			if (con != null && !con.isClosed()) {				
				con.close(); // 关闭连接对象
			}
			if (rs != null) {				
				rs.close(); // 关闭结果集对象
			}
		} catch (Exception e) {
			System.out.println(
					"\n提示:系统在关闭连接释放资源时发生异常!");
		}
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值