JDBC工具类


JDBC工具类

什么是JDBC工具类

通过上面案例需求我们会发现每次去执行SQL语句都需要注册驱动,获取连接,得到Statement,以及释放资源。发现很多重复的劳动,我们可以将重复的代码定义到某个类的方法中。直接调用方法,可以简化代码。而这个类就叫JDBC的工具类

编写JDBC工具类步骤

  1. 将固定字符串定义为常量
  2. 在静态代码块中注册驱动(只注册一次)
  3. 提供一个获取连接的方法static Connection getConneciton();
  4. 定义关闭资源的方法close(Connection conn, Statement stmt, ResultSet rs)
  5. 重载关闭方法close(Connection conn, Statement stmt)

具体代码

将驱动、连接、用户名、密码存储到一个properties里面,方便以后更改

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///20220815?serverTimezone=UTC
user=root
password=root

具体代码:

import java.sql.*;
import java.util.Properties;

public class utils {
    // 1.将固定字符串定义为常量,防止没有properties时无法使用   
    public static String driver = "com.mysql.cj.jdbc.Driver";
    public static String url = "jdbc:mysql:///20220815?serverTimezone=UTC";
    public static String user = "root";
    public static String password = "root";

    //加载驱动--因为只需要执行一次,所以使用静态代码块
    // 2.在静态代码块中注册驱动(只注册一次)
	// 当这个类加载到内存的时候就走这个静态代码块,再去触发Driver类中的静态代码块,主动注册
        /* 将四个参数抽取为一个jdbc.properties文件,放置在src目录下,
      	   然后通过Properties对象getProperty()方法获取每个值 */
    static{
        try {
            Properties pp=new Properties();
            pp.load(utils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            driver = pp.getProperty("driver");
            url = pp.getProperty("url");
            user = pp.getProperty("user");
            password = pp.getProperty("password");
        } catch (Exception ex) {
            //ex.printStackTrace();
            System.out.println("未找到配置文件,使用默认配置");
        }


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

    // 3.提供一个获取连接的方法static Connection getConneciton();
	// 我们面向JDBC编程
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }


	// 4.提供一个执行查询方法,用于直接执行查询语句
    /**
     * @param sql 查询语句
     * @param conn 连接名
     * @param params 设置的字段
     * @return 返回结果集
     * @throws SQLException
     */
    public static ResultSet executeQuery(String sql,Connection conn,Object...params) throws SQLException {
        //获取预处理对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //设置参数
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        return ps.executeQuery();
    }

	// 5.提供一个执行CUD方法,用于直接执行
    /**
     *
     * @param sql cud语句
     * @param conn 连接名
     * @param params 设置的字段
     * @throws SQLException
     */
    public static int execute(String sql,Connection conn,Object...params) throws SQLException {
        //获取预处理对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //设置参数
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        return ps.executeUpdate();
    }
	
	// 6.定义关闭资源的方法close(Connection conn, Statement stmt, ResultSet rs)
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {}
		}
		
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {}
		}
	}
	
	// 7.重载关闭方法close(Connection conn, Statement stmt)
	public static void close(Connection conn, Statement stmt) {
		close(conn, stmt, null);
	}
}

JDBC工具类v1.1

学习了连接池后,来更新JDBC工具类
导入hikaricp和slf4j的jar包

更改静态代码块内的获取Properties方式

//添加一个连接池变量
private static HikariDataSource dataSource;

static{
		Properties properties = new Properties();
		properties.setProperty("driverClassName", driver);
		properties.setProperty("jdbcUrl", url);
		properties.setProperty("username", user);
		properties.setProperty("password", password);
		
		try {
			properties.load(util.class.getClassLoader().getResourceAsStream("jdbc.properties"));
		} catch (Exception e) {
			System.out.println("未加载到配置文件,使用默认配置");
		}
		//加载到hikaricp连接池中
		HikariConfig hikariConfig = new HikariConfig(properties);
		dataSource = new HikariDataSource(hikariConfig);
    }

更改获取连接的方式

public static Connection getConnection() throws SQLException {
    return dataSource.getConnection();
}

添加回收连接方法

因为使用连接池,使用回收效率会更高

/**
* 回收连接
* @param connection
*/
public static void evictConnection(Connection connection){
   dataSource.evictConnection(connection);
}

v1.1全部代码

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class util {
    //连接字段保存为变量
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql:///20220815?serverTimezone=UTC";
    private static String user = "root";
    private static String password = "root";
    private static HikariDataSource dataSource;

    //加载驱动--因为只需要执行一次,所以使用静态代码块
    static{
        Properties properties = null;
        try {
            properties=new Properties();
            properties.load(util.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        } catch (Exception e) {
            properties.setProperty("driverClassName", driver);
            properties.setProperty("jdbcUrl", url);
            properties.setProperty("username", user);
            properties.setProperty("password", password);
            System.out.println("未加载到配置文件,使用默认配置");
        }

        HikariConfig hikariConfig = new HikariConfig(properties);
        dataSource = new HikariDataSource(hikariConfig);

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

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 回收连接
     * @param connection
     */
    public static void evictConnection(Connection connection){
        dataSource.evictConnection(connection);
    }

    /**
     * @param sql 查询语句
     * @param conn 连接名
     * @param params 设置的字段
     * @return 返回结果集
     * @throws SQLException
     */
    public static ResultSet executeQuery(String sql,Connection conn,Object...params) throws SQLException {
        //获取预处理对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //设置参数
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        return ps.executeQuery();
    }

    /**
     *
     * @param sql cud语句
     * @param conn 连接名
     * @param params 设置的字段
     * @throws SQLException
     */
    public static int execute(String sql,Connection conn,Object...params) throws SQLException {
        //获取预处理对象
        PreparedStatement ps = conn.prepareStatement(sql);
        //设置参数
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i+1,params[i]);
        }
        return ps.executeUpdate();
    }
}

Spring-JDBC

一个由Spring团队开发的JDBC的工具类,作用和DBUtils一样,是目前代替DBUtils产物。

使用步骤

//1.创建连接池
Properties pp = new Properties();
pp.load(test.class.getClassLoader().getResourceAsStream("jdbc.properties"));
HikariConfig hc = new HikariConfig(pp);
HikariDataSource ds = new HikariDataSource(hc);
//2.创建JdbcTemplate
JdbcTemplate jt = new JdbcTemplate(ds);
    1. 使用JdbcTemplate完成CRUD操作
//3.使用jdbcTemplate
int i = jt.queryForObject("select count(*) from user;", Integer.class);
//查询用户表的总条数
System.out.println(i);

//添加用户
jt.update("insert into user(name, pwd) values(?,?)", "张三", "123456");

//查询所有用户
List<User> list = jt.query("select * from user", new BeanPropertyRowMapper<User>(User.class));
System.out.println(list);

//删除用户
jt.update("delete from tuser where name = ?", "张三");

//更新用户
jt.update("update user set pwd = ? where id = ?", "123asd", "2");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值