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();
            }
        }
    }
    
  • 相关阅读:
    HihoCoder 1245:王胖浩与三角形 三角形边长与面积
    C++ 读写注册表
    Codestorm:Counting Triangles 查各种三角形的个数
    2015年10月之 叽里咕噜
    HDU 5523:Game
    Codestorm:Game with a Boomerang
    关于GPU-driver for linux的资料
    ACER NV47H75C 安装CUDA 驱动以及调整屏幕
    服务器GTX590安装CUDA
    观后感,读了几篇博文
  • 原文地址:https://www.cnblogs.com/techoc/p/13630151.html
Copyright © 2011-2022 走看看