mybatis基础_使用JDBC遇到的问题

博客介绍了使用JDBC连接方式查询数据时存在的不便。包括频繁创建、释放连接造成资源浪费;SQL硬编码,不利于维护和扩展;使用占位符设置参数,后期维护麻烦;结果处理硬编码,不利于维护。

使用JDBC的连接方式查询数据:

import java.sql.*;

public class JDBCDemo {
    /*连接参数常量*/
    private static final String JDBC_URL = "jdbc:mysql:///mybatis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8";
    private static final String USER = "root";
    private static final String PWD = "root";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            /*加载驱动*/
            Class.forName("com.mysql.jdbc.Driver");
            /*获得连接对象*/
            connection = DriverManager.getConnection(JDBC_URL, USER, PWD);
            /*SQL*/
            String sql = "select * from user where id = ?";
            /*将SQL传入*/
            preparedStatement = connection.prepareStatement(sql);
            /*设置SQL参数*/
            preparedStatement.setInt(1, 1);
            /*执行SQL 返回数据*/
            resultSet = preparedStatement.executeQuery();
            /*遍历结果集*/
            while (resultSet.next()) {
                System.out.println("id = " + resultSet.getInt("id") + "name = " + resultSet.getString("username"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            /*关闭所有连接*/
            if (resultSet != null) {
                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();
                }
            }
        }
    }
}

总结JDBC使用的使用有四点不便:

  1、使用时频繁的创建、释放连接,造成系统资源的浪费。

  2、SQL是硬编码在代码里面,不利于后期的维护以及扩展,耦合性过强。

  3、使用占位符的方式设置参数,在后期维护时比较麻烦(修改了SQL的条件,占位符的参数就要修改)。

  4、对结果的处理也是硬编码,非常不利于后期的维护。

转载于:https://www.cnblogs.com/l48x4264l46/p/10926894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值