数据库工具类

数据库工具类

通过学习我们知道,连接一个数据库很麻烦,使用完还要关闭,如果我们在一个项目中遍地都是开启关闭,那么代码会很冗余,所以我们能不能写一个数据库连接的工具类嘞?

**
 * @program: Dream
 * @description: 数据库工具类
 * @author: stop.yc
 * @create: 2022-03-18 10:57
 **/
public class DbUtil {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    /*配置信息,程序运行后,只要一次,就不会改变了,然后驱动加载也只需要一次,那么就是用静态代码块,程序运行后,运行一次*/
    static {
        try {
            //通过字节输入流,获取文件中的配置信息.
            InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
            //文件加载
            Properties properties = new Properties();
            properties.load(in);
            //获取
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //加载驱动(如果在这里出现NPE的话,看看是不是没有导入连接jar包)
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //外部调用获取连接方法,被CRUD工具类调用
    public static Connection getCon() throws Exception {
        return DriverManager.getConnection(url,username,password);
    }

    //外部调用关闭方法.被CRUD工具类调用
    public static  void close(Connection con,PreparedStatement ps,ResultSet rs)  {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       if(ps!=null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}



//包同级目录下,新建一个文件,db.properties,内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_dream?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456
    
    
    
/*关于展示,就请到另一篇文章看看,顺便学习一下CRUD的封装*/

数据库CRUD封装

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值