栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDBC自学总结梳理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDBC自学总结梳理

          寒假几天,在b站看了韩顺平老师的教学视频,收获很多。这里记录一下这几天学习JDBC的内容以便于日后复习。

        首先是获取连接,获取连接有几种方式。第一种如下:创建出driver对象(com.jdbc.mysql.Driver包中),使用driver的connect方法获取连接。

//使用创建driver对象方式获取连接
    @Test
    public void connection01() throws SQLException {
        Driver driver = new Driver();
        String url = "jdbc:mysql://localhost:3306/lrz_db03";
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "1230");
        Connection connect = driver.connect(url, properties);
        System.out.println("获取链接为" + connect);
    }

        第二种方式是使用driverManager的getConnection方法获取

//使用driverManager获取连接
    @Test
    public void connection02() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");//进行类加载
        String url = "jdbc:mysql://localhost:3306/lrz_db03";
        String user = "root";
        String password = "1230";
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

        第三种方式也是比前两种方式更灵活的是使用配置文件进行URL和用户名和密码的编写

 @Test
    public void connection03() throws IOException, SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\connection.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

        但最后的方式是使用数据库连接池的方式进行连接,这种方式大大减少性能消耗。这里使用德鲁伊(Druid)连接池进行连接,首先需要导入相应的jar包,使用配置文件进行连接的具体信息的编写,如密码、用户名、URL、最大连接数,最小连接数等。通过Properties的到配置文件后,通过以下代码即可获取连接

//通过德鲁伊来获取连接
Properties properties = new Properties();
properties.load(new FileInputStream("src\druid.properties"));
//获取连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
//通过连接池获取连接
Connection connection = dataSource.getConnection();

        获取连接后,就是对对数据库进行增删改查等操作。比如使用PrepareStatement进行查询,这里注意使用Statement会有SQL注入问题(有意思)

//执行语句 查询dog表
        PreparedStatement preparedStatement = connection.prepareStatement("select * from dog");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getString(1) + resultSet.getString(2));
        }

        这里使用executeQuery方法,返回resultset结果集对象,这个对象只能查询不能够进行数据的来回滚动读取。后续会改进。该对象的next方法,返回TRUE和FALSE,表示是否有下一个查询行,也有previous方法获取上一行数据。

        由于获取连接课关闭连接比较常用,所以可以封装成一个类及方法,以后可以直接调用该类的get_Connection和close_Connection来获取连接和关闭连接。

public class Utils {
    static DataSource dataSource;
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection get_Connection() throws SQLException {
        //得到连接池
        return dataSource.getConnection();
    }
   
    public static void close_Connection(Connection con, Statement sta, ResultSet res){
        try {
            if(con != null){
                con.close();
            }
            if(sta != null){
                sta.close();
            }
            if(res != null){
                res.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

        说到使用resultSet的问题,这里获得结果集后无法进行反复调用以及关闭不方便,所以使用Apache提供的DBUtils来将获取的结果进行进一层封装,变成对象。例如数据库中有actor表,有以下的属性。

         这里就可以创建一个actor对象,属性和上面一一对应。并加上set和get方法,无参有参构造器都写上。导入Apache的dbutils的jar包。创建queryRunner对象qr,使用qr对象来进行增删改查操作。 比如下面的query查询方法,这时返回的就是一个list集合,在query方法的第三个参数中,创建了一个BeanListHandler对象,qr对象在底层会自动将获取到的resultSet结果集进行进一步的对象封装并添加到一个list集合中,将该集合返回。关闭连接只需关闭连接即可,qr对象会将statement和resultset的连接关闭。

 @Test
    public  void test() throws SQLException {
        //先得到连接
        Connection connection = Utils.get_Connection();
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select * from actor";
        List query = queryRunner.query(connection, sql, new BeanListHandler<>(actor.class));
        System.out.println(query);
        Utils.close_Connection(connection, null, null);
    }

       查询单行和单行单列大同小异。执行dml操作则使用qr.updata(connection,sql)获取返回的影响行数。

        最后由于这种方式的SQL语句比较固定,不能通过参数传入,通用性不好,这里可以再进行进一步的封装变成DAO(数据访问对象)层。编写父类BasicDao。该类有Query Runner其中包含查询方法。该方法集成了上述所有的链接和关闭连接以及查询操作。以后根据数据库对象可创建相应的dao对象,继承BasicDao即可。

public class BasicDao {
    private QueryRunner qr = new QueryRunner();

    //开发通用dml方法,针对任意表
    public int update(String sql, Object... parameters) {
        Connection connection = null;
        try {
            connection = Utils.get_Connection();
            int update = qr.update(connection, sql, parameters);
            return update;
        } catch (SQLException throwables) {
            throw new RuntimeException();
        } finally {
            Utils.close_Connection(connection, null, null);
        }
    }

    //返回多个对象,即多行数据
    public List queryMulti(String sql, Class clazz, Object...parameters){
        Connection connection = null;
        try {
            connection = Utils.get_Connection();
            List query = qr.query(connection, sql, new BeanListHandler<>(clazz), parameters);
            return query;
        } catch (SQLException throwables) {
            throw new RuntimeException();
        } finally {
            Utils.close_Connection(connection, null, null);
        }
    }
}

        学习内容大致如上,如有错误敬请指正,最后感谢韩顺平老师!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/723178.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号