zoukankan      html  css  js  c++  java
  • JavaWeb基础之JdbcUtils工具类1.0

    2016年12月20日,第一次学习JDBC。看的是传智播客崔希凡老师的视频,东北口音很是风趣幽默,技术之牛让人膜拜。2017年9月21日,再次重温web知识,分享JdbcUtils工具类,用以接下来的开发更加简单 优雅......

    1. 在src下给出连接数据库的四大参数配置文件

      * 在src下创建dbconfig.properties文件

      * 给出下列键值对(下面以mysql为例)

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/数据库名称
    username=数据库用户名
    password=数据库密码

    2. 通过JdbcUtils工具获取连接

    /**
     * JdbcUtils v1.0
     * @author hui.zhang
     *
     */
    public class JdbcUtils {
    	private static Properties props = null;
    	static{
    		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{
    		return DriverManager.getConnection(props.getProperty("url"),
    				props.getProperty("username"),
    				props.getProperty("password"));
    	}
    }                                            
    

    3. 测试

    public class Demo{
        @Test
        public void test() throws Exception {
            Connection con = JdbcUtils.getConnection();
            System.out.println(con);
        }
    }

     * 控制台输出如下结果:com.mysql.jdbc.JDBC4Connection@62f47396

    4. 总结

      这是第一个版本的工具,适合初学JDBC的同学用来节省获取连接做简单增删改查,用内路径获取配置文件是为后期做成jar考虑,如果直接写死成src/xxx.properties,那么打成jar包会没有src的,这样做更加完善。接下来会分享出几个改版的JdbcUtils工具以及接下来学习的一些心得,敬请关注!

  • 相关阅读:
    常用日期函数介绍
    常用数学函数介绍
    oracle 常用sql字符函数介绍
    centos6.5 相关命令
    Kettle5.4.0 java.lang.OutOfMemoryError
    oracle多表连接方式Hash Join Nested Loop Join Merge Join
    CONNECT_BY_ROOT
    设置Oracle PL/SQL时间显示格式NLS_TIMESTAMP_FORMAT
    INSTR代替NOT LIKE
    多表插入
  • 原文地址:https://www.cnblogs.com/stefan95/p/7575262.html
Copyright © 2011-2022 走看看