自定义工具类jdbcUtils

package cn.taylor.demo5;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/*
 * v1.0
 */
public class JdbcUtils {

	private static Properties prop=null;
	
	//将加载文件和驱动类文件放在静态代码块中是为了让它只执行一次,加快速度
	

	static{
		
		//1.加载配置文件
		try{
			InputStream in=JdbcUtils.class.getClassLoader()
				.getResourceAsStream("dbconfig.properties");
		prop=new Properties();
		prop.load(in);	//给prop进行初始化,即加载dbconfig.properties文件到prop对象中
		}catch(IOException e){
			throw new RuntimeException(e);
		}
		
		//2.加载驱动类
		try{
			Class.forName(prop.getProperty("driverClassName"));
		}catch(ClassNotFoundException e){
			throw new RuntimeException(e);
		}
	}
	
	//3.调用DriverManager.getConnection()
	public static Connection getConnection() throws Exception{

		
		return DriverManager.getConnection(prop.getProperty("url"),
				prop.getProperty("username"),
				prop.getProperty("password"));
	}
}


猜你喜欢

转载自blog.csdn.net/roseTaylor/article/details/80290121