欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据库连接池JDBC

程序员文章站 2022-03-07 11:33:42
...
package util;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class JDBCORCALUtil2 {
//	public static final String driver = "oracle.jdbc.driver.OracleDriver";
//	public static final String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
//	public static final String name = "yyd";
//	public static final String pwd = "yyd";
	Connection con = null;// 链接对象
	PreparedStatement ps = null;
	ResultSet rs = null;
	public static Context ctx;
	public static DataSource ds;

	static{//只会执行一次,并且是第一次调用时候自动执行
		try {
			ctx=new InitialContext();
			ds=(DataSource) ctx.lookup("java:comp/env/jdbc/rentcar");
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
	}
	
//	public Connection getcon() {
//
//		try {
//			Class.forName(driver);
//			con = DriverManager.getConnection(url, name, pwd);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		return con;
//
//	}
	
	public Connection getcon() {

		try {
			con=ds.getConnection();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return con;

	}

	public void closeAll() {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

	
	public boolean update(String sql, Object...obj){
		int num=0;
		con = getcon();
		try {
	ps = con.prepareStatement(sql);
     if(obj!=null){
    	 
    	 for(int i=0;i<obj.length;i++){
    		 ps.setObject(i+1, obj[i]);
    	 }
     }
    num = ps.executeUpdate();
     
			 
		

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeAll();
		}
		return num>0;
	}
	
	
	public ResultSet select(String sql, Object...obj){
		
		con = getcon();
		try {	
			
	ps = con.prepareStatement(sql);
     if(obj!=null){
	for(int i=0;i<obj.length;i++){
		ps.setObject(i+1, obj[i]);
	}
}
		rs = ps.executeQuery();

  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	
	}
	return rs;	
	}	
		
	

}