JDBCUtils-JDBC工具类

JDBC操作中
无非就是
1.连接2.sql语句3.关闭
其中连接的关闭的语句如果是同一个数据库其实都是相同的

所以连接和关闭可以封装连接的释放来做一个工具类
进行更方便的调用
示例图
在这里插入图片描述
工具类代码

package yuan.hsp.JDBC;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
@SuppressWarnings("all")
//实现连接和关闭的JDBC工具类
public class JDBCUtils {
	//定义相关属性,因为只需要一份用static修饰
	private static String user;
	private static String password;
	private static String url;
	private static String driver;
	//用static初始化
	static {
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream("src\\pra.properties"));
			user=properties.getProperty("user");
			user=properties.getProperty("password");
			user=properties.getProperty("url");
			user=properties.getProperty("driver");
		} catch (IOException e) {//捕获异常
			throw new RuntimeException(e);//实际开发中一般转为一个运行异常抛出去
			//将编译异常转为运行异常,可以捕获或者默认处理
		}	
	}
	//获取连接
	public static java.sql.Connection getConnection() {
		try {
			return DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			throw new RuntimeException(e);//还是转运行异常
		}
	}
	//关闭资源
	//参数为可能需要关闭的资源
	public static void close(ResultSet set,Statement statement,Connection connection) throws SQLException {
		//参数用Statement既可以接收Statement也可以接收PreparedStatement
		
		//判断是否为null,比如可能不是查询就没有ResultSet这个传入null即可,然后不等于null就关闭
		if (set!=null) 
			set.close();
		
		if (statement!=null) 
			statement.close();
		
		if(connection!=null)
			connection.close();		
	}
	
}

工具类写完了肯定要看看能不能用,接下来就是使用环节
查询的话步骤差不多这里就不说了

package yuan.hsp.JDBC.jdbcutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

import org.junit.jupiter.api.Test;
@SuppressWarnings("all")
//演示JDBC工具类使用
public class dml {
@Test
	public void testDML() throws SQLException {
	Connection connection = null;
	//先组织sql语句
	String sql="update actor set name= ? where id = ? ";
	PreparedStatement prepareStatement=null;
	try {
		connection=JDBCUtils.getConnection(); 
		prepareStatement = connection.prepareStatement(sql);
		prepareStatement.setString(1, "周星驰");
		prepareStatement.setInt(2, 4);
		
		prepareStatement.executeUpdate();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	finally {
		JDBCUtils.close(null, prepareStatement, connection);
	}

}
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小袁拒绝摆烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值