jdbc的简单封装1-连接优化

jdbc的简单封装

jdbc.properties文件代码如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_db?useUnicode=true&characterEncoding=utf-8
username=root
password=1234

一、对连接的封装

//对jdbc的重用性代码进行封装
//=================连接和关闭====================
public class DbUtils2 {
    //获取连接
    private  static  Properties properties = new Properties();
    static {
       try{
       		//通过类自带的资源加载器加载文件资源
           //========jdbc.properties放在同src同目录下========
           //对于/jdbc.properties路径一定要正确
           InputStream is = DbUtils2.class.getResourceAsStream("/jdbc.properties");
           //创建Properties 属于Map集合的分支,可以键值对
           Properties properties = new Properties();
           //load方法
           properties.load(is);
           //只加载一次
           Class.forName(properties.getProperty("driver"));
       }catch (Exception e){
           e.printStackTrace();
       }
    }
    public static Connection getConnection() {
        Connection connection = null;
        try {
          
            connection = DriverManager.getConnection(
                    properties.getProperty("url"),
                    properties.getProperty("username"),
                    properties.getProperty("password")
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    } 

二、对关闭资源的封装

//关闭连接
//=======遵循先开后关原则===========
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
       try {
           if(resultSet!=null){
               resultSet.close();
           }
           if(statement!=null){
               statement.close();
           }
           if(connection!=null){
               connection.close();
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}

三、测试

package com.itheima.utils;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestJdbc {
    @Test
    public void testSelect() throws Exception {
        Connection connection = DbUtils.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from student;");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
            System.out.println(resultSet.getInt(3));
            System.out.println(resultSet.getString(4));
        }
        DbUtils.closeAll(connection,preparedStatement,resultSet);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值