package com.seeyon.apps.src_contract.lease.util;

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


/**
 * sql执行工具类
 * 2021-06-08
 * @author huangzhengguo
 *
 */
public class BaseUtil {

	
	PreparedStatement ps = null;
	ResultSet res = null;
	Connection conn =null;
	/**
	 * sql查询工具
	 * @param sql sql语句
	 * @param params sql参数  
	 * @return 结果集
	 */
	public ResultSet executeQuery(String sql, Object[] params)
	{
		conn = JdbcUtil.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0; i < params.length; i++){
				ps.setObject(i+1, params[i]);
			}
			res = ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
	/**
	 * sql更新工具
	 * @param sql
	 * @param params
	 * @return
	 */
	public int executeUpdate(String sql, Object[] params)
	{
		int res = 0;
		conn = JdbcUtil.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0; i < params.length; i++)
			{
				ps.setObject(i+1, params[i]);
			}
			res = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
	
	
	public void close() {
		release(res,null,conn,ps);
	}
	//定义一个释放资源的方法;  
		/*
		 * 定义一个方法： 释放资源： 直接将rs stmt conn 全部释放： 
		 */
		public static void release(ResultSet rs ,Statement stmt , Connection conn,PreparedStatement ps){
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				rs=null;
			}
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				stmt=null;
			}
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				conn=null;
			}
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				ps=null;
			}
			
		}
}
