⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connectionpool.java

📁 Eclipse+Struts+MYSQL的留言板,Struts开发入门程序Struts版 这个是一Struts实例,喜欢学习JAVA的朋友可以下载去看看 可以用作Struts入门程序,本人开发
💻 JAVA
字号:
package com.dimscar.util;

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

import org.apache.log4j.Logger;

/**
 * 数据库连接池
 * 
 * @author Dim.Scar
 * 
 */

public class ConnectionPool {
	
	public Logger log = Logger.getLogger(ConnectionPool.class);

	public Connection con = null; // 连接数据库 ///

	private Statement sm = null;

	private ResultSet rs = null; // 结果集对象 ///

	static private ConnectionPool conpool = null;
	
	public ConnectionPool(){
		
	}
	/**
	 * 获得一个数据池的实例
	 * @return 数据池实例
	 */
	public static  ConnectionPool getInstance(){
		if(conpool == null){
			conpool = new ConnectionPool();
		}else{
			return conpool;
		}
		return conpool;
	}
	
	/**
	 * 加载数据库驱动
	 * 
	 * @throws SQLException
	 */
	public void onLoadDriver() throws SQLException {
		try {
			//System.out.println("数据库连接开始..........");

			// 驱动程序
			Class.forName(Constants.DB_DRIVER).newInstance();

			// 数据库连接
			if (con == null || con.isClosed()) {

				con = DriverManager.getConnection(Constants.DB_URL,
						Constants.DB_USER, Constants.DB_PASSWORD);

				sm = con.createStatement();
			}
			//System.out.println("数据库连接成功..........");

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("数据库连接失败..........");

		}
	}

	/**
	 * 对数据库插入,更新,删除等操作
	 * 
	 * @param sql
	 *            操作SQL
	 * @return 插入,更新,删除等操作是否成功.
	 */
	public boolean update(String sql) {
		/**
		 * 操作是否成功
		 */
		boolean flag = true;
		
		log.info("数据库操作SQL:"+sql);
		
		try {
			// 先加载数据库驱动
			this.onLoadDriver();

			int num = sm.executeUpdate(sql);
			
			if(num == 0){
				return false;
			}else{
				return true;
			}

		} catch (SQLException e) {

			flag = false;

			e.printStackTrace();

		} finally {

			this.closeDriver();
		}

		return flag;
		
	}

	/**
	 * 执行数据查找
	 */
	public ResultSet Query(String sql) {

		log.info("数据库操作SQL:"+sql);
		
		try {
			this.onLoadDriver();

			rs = sm.executeQuery(sql);

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			// this.closeDriver();
		}
		return rs;
	}

	/**
	 * 关闭数据库连接
	 */
	public void closeDriver() {
		try {
			if (con != null) {
				con.close();
				sm.close();
				con = null;
				sm = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -