1、在src目錄下需要寫對應的配置文件 dbconfig.properties(四大參數(shù))
2、優(yōu)化代碼,當多次調用時,只加載類一次
3、后期將繼續(xù)更新
/**
* v1.0
* @author KimJun
*
*/
public class JdbcUtils {
private static Properties props = null;
//只在JdbcUtil類被加載時執(zhí)行一次
static{
//給props進行初始化,即加載dbconfig.properties文件到props對象中
try{
InputStream in = JdbcUtils.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
props = new Properties();
props.load(in);
} catch(IOException e){
throw new RuntimeException(e);
}
//加載驅動類
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//獲取連接!
public static Connection getConnection() throws SQLException {
/*
* 得到Connection
*/
return DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
}
}