BaseDao数据库辅助类

package org.news.dao;

/**
 * 操作数据库的通用类
 * @author Think
 *
 */

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

import javax.naming.*;
import javax.sql.DataSource;

public class BaseDao {

	protected Connection connection = null;
	protected PreparedStatement preparedStatement = null;
	protected ResultSet resultSet = null;

	// 1、打开数据库

	public Connection getConnection() {
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/managingpeople_1?useUnicode=true&characterEncoding=utf-8", "root","123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

	/*
	 * public Connection getConnection() {
	 * 
	 * try {
	 * 
	 * Context ctx=new InitialContext(); DataSource
	 * dataSource=(DataSource)ctx.lookup("java:comp/env/jdbc/news");
	 * connection=dataSource.getConnection();
	 * 
	 * } catch (Exception e) {
	 * 
	 * e.printStackTrace(); } return connection; }
	 */
	// 2、关闭所有资源

	public void closeAll(Connection connection,
			PreparedStatement preparedStatement, ResultSet result) {
		if (result != null) {
			try {
				result.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (preparedStatement != null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 3、增、删、改通用方法
	public int executeUpdate(String sql, Object... param) {
		int num = 0;// 影响行数
		connection = this.getConnection();
		try {
			preparedStatement = connection.prepareStatement(sql);
			// 为参数进行赋值
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					preparedStatement.setObject(i + 1, param[i]);
				}
			}
			// 执行SQL语句
			num = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.closeAll(connection, preparedStatement, null);
		}
		return num;
	}

	/**
	 * 执行查询操作 备注:此方法适用于纯查询使用,若是输入加查询需要另外设计
	 * 
	 * @param sql
	 *            语句
	 * @return
	 */
	public ResultSet executeQuery(String sql, Object... param) {

		connection = this.getConnection();
		try {
			// 发送SQL语句
			preparedStatement = connection.prepareStatement(sql);
			// 参数进行赋值
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					preparedStatement.setObject(i + 1, param[i]);
				}
			}
			// 返回结果集
			resultSet = preparedStatement.executeQuery();

		} catch (Exception e) {

			closeAll(connection, preparedStatement, resultSet); // 关闭所有连接

			System.out.println("发生异常:\n" + e.getMessage());

		}
		return resultSet;
	}
}

发布了108 篇原创文章 · 获赞 46 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_44739706/article/details/104525070