zoukankan      html  css  js  c++  java
  • mybatis基础_使用JDBC遇到的问题

    使用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、对结果的处理也是硬编码,非常不利于后期的维护。

  • 相关阅读:
    软件工程第八周
    e课表项目第二次冲刺周期第十天
    蓝桥杯java历年真题及答案整理41~56
    蓝桥杯java历年真题及答案整理21~40
    蓝桥杯java历年真题及答案整理1~20.md
    异序二分查找 二分查找方程根 二分查找重复元素最后一个
    软件说明
    遗传算法--句子匹配
    Matlab学习笔记
    使用TenforFlow 搭建BP神经网络拟合二次函数
  • 原文地址:https://www.cnblogs.com/l48x4264l46/p/10926894.html
Copyright © 2011-2022 走看看