JDBC之BaseDao类

package com.it.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 数据库操作工具类
 * 7个属性 4个方法(连接方法 关闭资源方法 通用查询方法 通用增删改方法)
 */
public class BaseDao {
	private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
	private static final String USERNAME = "system";
	private static final String PASSWORD = "ok";
	//con
	public Connection con = null;
	//pstmt
	public PreparedStatement pstmt = null;
	//rst
	public ResultSet rst = null;
	/*
	 * 获取连接方法
	 */
	public void getCon(){
		try {
			Class.forName(DRIVER);
			con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 关闭资源 从内到外关闭
	 */
	public void closeAll(){
		try {
			if(rst != null){
				rst.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if(pstmt != null){
				pstmt.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if(con != null){
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * sql:sql语句
	 * params:参数(填充sql中?的参数数组)
	 */
	public void commonQuery(String sql,Object[]params){
		try {
			//获取连接
			this.getCon();
			//获取执行sql对象
			pstmt = con.prepareStatement(sql);
			//对?处理,下标从1开始
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i+1, params[i]);
			}
			//获取结果集
			rst = pstmt.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public int commonUpdate(String sql,Object[]params){
		int r = -1;
		try {
			//获取连接
			this.getCon();
			//获取执行sql对象
			pstmt = con.prepareStatement(sql);
			//对?处理
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i+1, params[i]);
			}
			//获取受影响行数
			r = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return r;
	}
}

原文地址:https://www.cnblogs.com/archermeng/p/7537453.html