通过 servletContext 得到 数据源,进而得到connection

时间:2023-02-17 09:55:05
DBOperation:
package com.community.util;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DBOperation {
	private PreparedStatement stsm;
	private static Logger log = LoggerFactory.getLogger(DBOperation.class);
	public void excuteUpdate(String sql,Object[]values,ServletContext sc)
	{
		try {
			stsm = DBConnection.getConnection(sc).prepareStatement(sql);
			if(values!=null && values.length>0)
			{
				for(int i=0 ; i<values.length ;i++)
				{
					stsm.setObject(i+1, values[i]);
				}
			}
			stsm.executeUpdate();
		} catch (SQLException e) {
			log.error("数据更新错误!",e);
		} finally {
			DBConnection.closeConnection();
		}
	}
	
}


package com.community.util;

import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import org.logicalcobwebs.proxool.ProxoolDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class DBConnection {
	private static Connection conn;
	private static Logger log = LoggerFactory.getLogger(DBConnection.class);

	/**
	 * 获得数据库连接
	 * 
	 * @return
	 */
	public static synchronized Connection getConnection(ServletContext sc) {
		init(sc);
		return conn;
	}

	/**
	 * 初始化数据库连接
	 */
	private static void init(ServletContext sc) {
		try {
			//PropUtils p = new PropUtils();
			//p.loadFile("jdbc.properties");
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
			//new FileSystemXmlApplicationContext();
			ProxoolDataSource prox = (ProxoolDataSource)ctx.getBean("dataSource");
			// 获取连接
			conn =prox.getConnection();
			// Class.forName(p.getValue("db.driver"));
			// conn =
			// DriverManager.getConnection(p.getValue("db.url"),p.getValue("db.user"),p.getValue("db.password"));
		} catch (SQLException e) {
			log.error("数据库连接错误!", e);
		}catch(Exception e){
			log.error("数据库连接错误!", e);
		}
	}

	/**
	 * 关闭数据库连接
	 */
	public static void closeConnection() {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				log.error("数据库关闭错误!", e);
			}
		}
	}
//	public static void main(String[] args) {
//		init();
//	}
}