Java教程

99%的文章均为原创,转载请注明~~~~视频教程~~可以到www.rjpx.net 分享

例6:总结数据库连接的各种方式

下面通过综合的例子来说明各种数据库的连接。

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;
	}
}


阅读更多
个人分类: Java
想对作者说点什么? 我来说一句

JAVA与SQLServer数据库连接总结

2013年04月26日 12KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭