jdbc的工具类封装

1 . 对于每个类基本要重复使用的代码,我们可以进行封装在一个类中,使用的时候直接调用这个类的方法就行了.
2 . 下面是工具封装类的三种方式.
第一种方法:

public static Connection getconn() {
            Connection connection = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                String url="jdbc:mysql://localhost:3306/LM02";
                connection = DriverManager.getConnection(url,"root","123");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return connection;
    }

第二种:

//按照流的方式读取
    @Test
    public   void test1() throws IOException {
        //1.获取属性对象properties
        Properties properties =new Properties();
        //1.1 把属性文件资源配置当作流进行读取,参数只需要写相对src的目录
        //getResourceAsStream()读指定文件内容以流的形式,该方法是ClassLoader类中  (装载class文件)
        // TestReadProperties.class.getClassLoader()获取当前类的类加载器对象
        InputStream inStream = TestReadProperties.class.getClassLoader().getResourceAsStream("dbinfo.properties");
        //2.装载属性文件
        properties.load(inStream);

        String  driverClass  = properties.getProperty("driverClass");
        String  url  = properties.getProperty("url");
        String  user  = properties.getProperty("user");
        String  password  = properties.getProperty("password");
        System.out.println(driverClass+"=="+url);
        System.out.println(user+"=="+password);


    }

第三种:

//第三种封装了第二种
    @Test
    public   void test2() {
        //获取资源文件对象(参数只填文件名,相对路径)
        ResourceBundle resourceBundle =ResourceBundle.getBundle("dbinfo");
        System.out.println("===="+resourceBundle.getString("driverClass"));

    }

注意上面的路径是相对路径,是相对于src来说的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值