一只会飞的旺旺
文章152
标签131
分类7
MyBatis学习笔记一

MyBatis学习笔记一

小卖铺上新啦!ChatGPT账号大甩卖! 一键直达

一.原始JDBC连接实现

1.pom.xml添加mysql驱动依赖


<dependencys>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
    </dependency>
    <!--lombok依赖,自动生成set,get方法-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.22</version>
        <scope>compile</scope>
    </dependency>
</dependencys>

2.编写代码

执行类: JdbcConnect

public class JdbcConnect {

    public static void main(String[] args) {

        User user = new User();

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Connection connection = null;

        try {
            // 1.加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2.获取连接配置,进行连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false", "root", "root");
            // 3.获取执行的SQL语句
            String sql = "select * from user where username = ?";
            preparedStatement = connection.prepareStatement(sql);
            // 4.设置占位符的值,执行查询
            preparedStatement.setString(1, "测试");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                // 5.处理结果集映射
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                user.setId(id);
                user.setUserName(username);
            }
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.资源关闭
            if (null != resultSet) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

实体类: User


@Data
public class User {

    private Integer id;

    private String userName;
}

3.JDBC问题总结

  • 数据库连接创建,释放频繁,浪费系统资源
  • SQL语句硬编码
  • SQL参数设置存在硬编码
  • 结果解析存在硬编码
微信支付码 微信支付
支付宝支付码 支付宝支付