JDBC工具类

JDBC工具类

为什么要写JDBC工具类?

在学习jdbc工具类之前,你会很清晰的发现,大量重复的代码,既浪费时间又浪费资源,所以通过一个工具类可以轻松的解决代码书写时间!

工具类的作用
  1. 实现注册驱动连接对象的获取
  2. 释放资源

所有操作前需要导包

需要导入包:mysql-connector-java-5.1.20-bin.jar
注意:根据自己电脑软件情况来导入包,有的需要的是8.0的版本,作者需要的是5.1的版本,这些都可以在网上搜索下载。
https://mvnrepository.com/artifact/mysql/mysql-connector-java

完整代码实现
JDBCUtils.java

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

    static {
        try {
            //1. 创建properties集合类
            Properties pro = new Properties();
            //2. 获取文件
            URL res = JDBCUtils.class.getClassLoader().getResource("jdbc.properties");
            String path = res.getPath();
            //3. 加载文件
            pro.load(new FileReader(path));
            //4. 获取数据,赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //5. 注册驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取连接
     */
    public static Connection getConnection() throws Exception{
        return DriverManager.getConnection(url,user,password);
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt, Connection conn){
        close(null,stmt,conn);
    }

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

配置文件jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbl
/*
如果导入的包是8以上的版本,是需要设置编码和时区的,直接在数据库名后加上
"?useUnicode=true&characterEncoding=utf-8&useSSL=false"
例如:url=jdbc:mysql://localhost:3306/dbl?useUnicode=true&characterEncoding=utf-8&useSSL=false
*/      
user=root
password=123456

这样一个JDBC工具类就完成了,之后的调用如下所示:

Connection con = JDBCUtils.getConnection();

留个赞再走吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值