美文网首页
JdbcUtils1.0小工具

JdbcUtils1.0小工具

作者: Kim140 | 来源:发表于2018-03-26 11:34 被阅读0次

1、在src目录下需要写对应的配置文件 dbconfig.properties(四大参数)
2、优化代码,当多次调用时,只加载类一次
3、后期将继续更新

/**
 * v1.0
 * @author KimJun
 *
 */
public class JdbcUtils {
    private static Properties props = null;
    
    //只在JdbcUtil类被加载时执行一次
    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"));
    }
}

相关文章

网友评论

      本文标题:JdbcUtils1.0小工具

      本文链接:https://www.haomeiwen.com/subject/aualcftx.html