JDBCUtils 工具类

在我们使用JDBC来连接数据库的时候,会发现,需要配置的东西很懂,而且每次使用的时候都是要重新开始配置,这样大大的增加了使用JDBC的速度,因此,我们可以将哪些需要重复配置的东西抽取出来,成为Java里面的工具类,需要配置的时候,直接JDBCUtil.就可以配置成功了

package com.mayikt.utils;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    //1.将构造方法私有化,------工具类  不需要new出来,直接类名.方法名直接调用
    private JdbcUtils(){

    }
    //2.定义工具类,需要 声明  变量
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;

    //3.使用静态代码块,给我们声明好的变量赋值
    static{

        try{
            //1读取config.properties IO 路径  相对路径
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");

            //2赋值给我们声明好的变量
            Properties properties = new Properties();
            properties.load(resourceAsStream);
             driverClass= properties.getProperty("driverClass");
                url= properties.getProperty("url");
                user= properties.getProperty("user");
           password  =   properties.getProperty("password");
            //3注册驱动
            Class.forName(driverClass);
        }catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }


    //4.封装连接方法
    public static Connection getConnection() throws SQLException {
       try{
         Connection connection = DriverManager.getConnection(url, user, password);
           return connection;
       }catch(Exception e){
           e.printStackTrace();
           return null;
       }
    }

    //释放连接方法
    public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection){
       try{


           if (statement != null)
               statement.close();

           if (connection != null)
               connection.close();


       } catch (SQLException throwables) {
           throwables.printStackTrace();
       }
    }





    public static void main(String[] args){
        System.out.println(JdbcUtils.driverClass);
    }

    //设置方法开启事务

    public static void beginTransaction(Connection connection) throws SQLException {
        connection.setAutoCommit(false);
    }

    //设置方法提交事务
    public static void commitTransaction(Connection connection) throws SQLException {
        connection.commit();
    }

    public static void rollBackTransaction(Connection connection) throws SQLException {
        if (connection!=null){
            try{
                connection.rollback();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值