jdbc的工具类封装

来源:互联网 发布:电脑专业录音软件 编辑:程序博客网 时间:2024/06/10 13:05

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来说的

原创粉丝点击