2. Get the database connection (Silicon Valley, yet notes) by DriverManager

DriverManager is driven management class.

public static Connection getConnection() throws Exception,{
	//1.准备连接数据库的4个字符串
	//驱动的全类名
	String driverClass=null;
	String jdbcUrl=null;
	String user=null;
	String password=null;
	//读取类路径下的jdbc.properties文件中连接数据库的4个字符串
	ClassLoader loader = Thread.currentThread().getContextClassLoader();
	Properties properties=new Properties();
	properties.load(loader.getResourceAsStream("jdbc.properties"));
	driverClass=properties.getProperty("driver");//读取接口类型
	jdbcUrl=properties.getProperty("jdbcUrl");
	user=properties.getProperty("user");
	password=properties.getProperty("password");
	//2.加载数据库驱动程序(对应的Driver实现类中有注册驱动的静态代码块注册驱动)
	//DriverManager.registerDriver((Driver) Class.forName(driverClass).newInstance());
        //可注册多个驱动程序
	Class.forName(driverClass);
	//3.调用DriverManager的getConnection(url,user,password)获取数据库连接
	Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
	return connection;
}

1) may be obtained through a database connection overloaded getConnection () method, is more convenient.

2) may manage the plurality of drivers simultaneously: if a plurality of registered database connection, the call getConnection () method when different parameters passed, i.e., returns a different database connections.

Published 90 original articles · won praise 48 · views 10000 +

Guess you like

Origin blog.csdn.net/Asher_S/article/details/90240815