JDBC工具类

package com.wpcweb.bank.utils;

import javax.management.remote.rmi._RMIConnection_Stub;
import java.sql.*;
import java.util.ResourceBundle;

/**
 * @author 一介草莽子
 * version 1.0
 */
@SuppressWarnings({"all"})
//JDBC工具类
public class DBUtils {
    //获得配置文件里的数据
    private static ResourceBundle Bundle = ResourceBundle.getBundle("resources/jdbc");

    //获得数据
    private static String driver = Bundle.getString("driver");
    private static String url = Bundle.getString("url");
    private static String user = Bundle.getString("user");
    private static String password = Bundle.getString("password");

    //获得驱动

    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //构造器已优化是为了不让别人创建对象因为是工具类全是静态方法
    private DBUtils() {
    }

    //获得连接
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    //关闭连接
    public static void close(Connection conn, PreparedStatement ps, ResultSet  rs){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}

1.创建配置文件

2.创建工具类(构造器私有化避免用的人创建对象因为里面全是静态方法用不到创建对象)

3.利用ResourceBundle.getBundle("resources/jdbc");获得配置问价里面的内容

4.获得的驱动 Class.forName(driver);只需要获取一次所以放到静态代码块

5.创建获取连接方法(静态的)

6.创建关闭连接的方法(静态的)

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02
user=root
password=4653long

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值