• mybatis学习笔记


    jdbc程序

    public static void main(String[] args) {
            Connection connection = null;//数据库连接
            PreparedStatement preparedStatement = null;//预编译的Statement
            ResultSet resultSet = null;//结果集
            try {
                // 加载驱动
                Class.forName("com.mysql.jdbc.Driver");
                // 创建连接
                connection = (Connection) DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/mybatis_day01?characterEncoding=utf-8", "root", "176166");
                // 定义sql语句
                String sql = "select * from user where username=?";
                preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
                preparedStatement.setString(1, "joan");
                resultSet = preparedStatement.executeQuery();
                // 遍历结果集
                while (resultSet.next()) {
                    System.out.println(resultSet.getString("id") + "" + resultSet.getString("username"));
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(resultSet!=null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(preparedStatement!=null) {
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(connection!=null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        }

    1 使用jdbc原生问题

      1 数据库频繁的链接开启和关闭,造成数据库资源浪费,影响数据库性能

      设想:使用数据库连接池管理数据库连接

      2 sql语句为硬编码到java代码中,不利于维护

      设想:将sql语句配置到xml文件中
      3 向preparedStatement中设置参数,设置占位符号位置,以及对应的参数值属于硬编码。
      设想:将sql语句及占位符和全部参数配置在xml中

      4 从resultSet中遍历结果集数据时存在硬编码
      设想:将查询结果集,自动映射成java对象

    2 mybatis 框架

     mybatis是一个持久层的框架。让程序将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成(半自动化,大部分需要程序员编写sql)满足需要的sql语句。向prepaerdStatement中的输入参数自动进行输入映射,将结果集映射成java对象(输出映射

      

      

  • 相关阅读:
    python小练习
    python学习笔记
    google测试之道读书笔记一
    webservice头部认证
    我们需要什么样的测试?
    pt-ioprofile在CentOS7上无法运行的解决办法
    推荐Nginx系列文章
    linux开启coredump的3种方法
    55, select/poll returned error
    centos ftp安装
  • 原文地址:https://www.cnblogs.com/joan-HTY/p/9012693.html
Copyright © 2020-2023  润新知