package com.itjob.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Hashtable;

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

public class DBCon {

	// 通过JDBC-ODBC桥获得连接
	public static Connection getOdbcCon(String datasourcename, String name,
			String password) throws ClassNotFoundException, SQLException {
		String url = "jdbc:odbc:";
		Connection con = null;
		con = DriverManager.getConnection(url + datasourcename, name, password);
		return con;
	}

	// 通过SQLSERVER的三个驱动，连接SQLSERVER2000数据库
	public static Connection getSQLServerCon(String name, String password)
			throws ClassNotFoundException, SQLException {
		String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433";
		Connection con = null;
		Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
		con = DriverManager.getConnection(url, name, password);
		return con;
	}

	// 通过ORACLE的驱动，连接ORACLE数据库
	public static Connection getOracleCon(String name, String password)
			throws ClassNotFoundException, SQLException {
		Connection con = null;
		Class.forName("oracle.jdbc.driver.OracleDriver");
		// 获得连接 oracle数据库的端口号为：1521 数据服务器的名字叫goudan(作者外号)
		String url = "jdbc:oracle:thin:@127.0.0.1:1521:goudan";
		con = DriverManager.getConnection(url, name, password);
		return con;
	}

	// 通过数据源获得连接
	public static Connection getConnectionFromDataSource(String filePath)
			throws javax.naming.NamingException, SQLException {
		Connection con = null;
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.fscontext.RefFSContextFactory");
		Context ctx = new InitialContext(env);
		DataSource ds = (DataSource) ctx.lookup(filePath);
		con = ds.getConnection();
		return con;
	}

	// 通过连接池获得连接
	public static Connection getConnectionFromPooledDataSource(String filePath)
			throws javax.naming.NamingException, SQLException {
		Connection con = null;
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.fscontext.RefFSContextFactory");
		Context ctx = new InitialContext(env);
		ConnectionPoolDataSource ds = (ConnectionPoolDataSource) ctx
				.lookup(filePath);
		PooledConnection pc = ds.getPooledConnection();
		con = pc.getConnection();
		return con;
	}
}
