java连接oracle 数据源

 

 

import java.sql.Connection;
import java.sql.SQLException;

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

import org.apache.commons.dbcp.BasicDataSource;

/**
 * 数据库帮助类,式单例模式
 * 
 * @author shenlin
 * 
 */
public class DBHelper {
	private DataSource ds = null;
	private static final DBHelper help = new DBHelper();

	private DBHelper() {
		try {
			Context context = new InitialContext();
			ds = (DataSource) context.lookup("java:comp/env/jdbc/scott");

			if (ds == null) {
				BasicDataSource basicds = new BasicDataSource();
				basicds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
				basicds.setUsername("scott");
				basicds.setPassword("tiger");
				basicds.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:ntcsoft");
				ds = basicds;
			}

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("初始化数据源" + ds);
	}

	public static DBHelper getInstance() {
		return help;
	}

	/**
	 * 获得数据库连接(先调用静态方法获得唯一实例,然后调用该方法获得数据库连接) 线程安全的
	 * 
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {
		System.out.println(ds.getClass().getName());
		if (ds != null) {
			synchronized (ds) {
				return ds.getConnection();
			}
		} else
			return null;
	}

}

 

 

 

你可能感兴趣的:(java,apache,oracle,sql,jdbc)