jdbc工具类

定义配置文件放在src目录下

#数据库连接路径
url=jdbc:mysql://localhost/day16
#登录用户名
username=root
#登录密码
password=root
#注册驱动
driver=com.mysql.jdbc.Driver

数据库连接工具类

package cn.itcast.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String url;
    private static String users;
    private static String password;
    private static String driver;

    /*
    * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
    * */
    static{
        //读取资源文件获取值
        Properties pro = new Properties();
        try {
            //获取src路径下文件的方式-->ClassLoader
            ClassLoader cl = JDBCUtils.class.getClassLoader();
            URL res = cl.getResource("jdbc.properties");
            String path = res.getPath();
            pro.load(new FileInputStream(path));
            url = pro.getProperty("url");
            users = pro.getProperty("users");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");

//            注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
    /*
    * 获取连接
    * @return 连接对象
    * */


    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,users,password);
    }


    /*
     * 释放资源
     * */
    public static void close(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Statement stmt, Connection conn, ResultSet rs){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs !=null ){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值