zoukankan      html  css  js  c++  java
  • 封装JDBC工具类

    封装JDBC工具类

    • 在实际JDBC的使用中,存在着大量的重复代码:例如连接数据库、关闭数据库等这些操作!
    • 我们需要把传统的JDBC代码进行重构,抽取出通用的JDBC工具类!以后连接的任何数据库、释放资源都可以使用这个工具类

    工具类核心思想

    重用性方案

    • 封装获取连接、释放资源两个方法
      • 提供public static Connection getConnection()方法。
      • 提供public static void closeAll(Connection connection,Statement statement,ResultSet resultSet)方法。

    跨平台方案

    • 定义public static final Properties properties=``new Properties();//读取配置文件的Map

    跨平台实现

    src目录下新建db.db.properties文件

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/jdbc
    username=root
    password=root
    

    工具类代码:

    package com.qf.jdbc2;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    public class DBUtils {
        private static final Properties PROPERTIES = new Properties();//存储配置文件的Map
    
        static {
            try {
                //选择读取文件的路径
                InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
                PROPERTIES.load(is);
                Class.forName(PROPERTIES.getProperty("driver"));
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        //连接数据库
        public static Connection getConnection() {
            Connection connection = null;
            try {
                connection = DriverManager.getConnection(PROPERTIES.getProperty("url"),
                        PROPERTIES.getProperty("username"),
                        PROPERTIES.getProperty("password"));
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            return connection;
        }
    
        //释放资源
        public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    
  • 相关阅读:
    COMMIT WORK AND WAIT 是在WAIT什么
    BINARY SEARCH in read table statement
    SAP 金额在表中的存储及货币转换因子
    REUSE_ALV_POPUP_TO_SELECT的使用技巧
    SAPScript、Smartforms动态打印图像或者背景图片
    SAP_Web_Service开发配置
    SAP中关于用户IP信息的获取(转载)
    DevExpress控件开发常用要点(项目总结版)
    鼠标指向表格时 显示更多信息 toolTipController1
    DevExpress组件之——TreeList组件
  • 原文地址:https://www.cnblogs.com/techoc/p/13630151.html
Copyright © 2011-2022 走看看