JavaWeb项目的数据库访问简单基础类

package com.etc.dao;

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

/** 数据库访问基础类 */
public class BaseDao {
	//String driver="com.mysql.cj.jdbc.Driver"; //mysql8	
	//String url="jdbc:mysql://localhost:3306/iotdemo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";//mysql8
	String driver="com.mysql.jdbc.Driver"; //mysql5
	String url="jdbc:mysql://localhost:3306/myjob";//mysql5 
	String user="root";
	String password="root";
	
	/**
	 * 获得数据库连接
	 * 
	 * @return 数据库连接对象
	 */
	public Connection getConnection() {
		Connection conn = null;// 数据库连接对象
		if (conn == null) {
			try {
				Class.forName(driver);// 加载驱动
				conn = DriverManager.getConnection(url, user, password);// 建立连接
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return conn;
	}

	/**
	 * 关闭资源
	 */
	public void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 增删改通用方法
	 * 
	 * @param sql
	 *            执行增删改的SQL语句
	 * @param args
	 *            参数数组
	 * @return 受影响行数
	 */
	public int executeUpdate(String sql, Object... args) {
		int result = -1;
		PreparedStatement ps = null;// 预编译对象
		Connection conn = this.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					ps.setObject(i + 1, args[i]);
				}
			}
			result = ps.executeUpdate();// 执行增删改
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll(null, ps, conn);
		}
		return result;
	}
}

  

原文地址:https://www.cnblogs.com/rask/p/13187936.html