JDBC工具类的创建和使用

在编写JDBC的代码时,存在很多代码冗余的地方,比如数据库驱动的连接,释放资源等操作,那么接下来就来写一个JDBC的工具类,它将更好的方便你的使用。

在项目中创建一个类,名称为JDBCUtils。代码如下:

package itwcn.com.utils;

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

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();
			
			//获取src路径下的文件方式----------->ClassLoader		类加载器
			ClassLoader classloader = JDBCUtils.class.getClassLoader();
			URL res = classloader.getResource("jdbc.properties");
			String path = res.getPath();
			System.out.println(path);
			
			//2.加载文件
//			pro.load(new FileReader("src/jdbc.properties"));
			pro.load(new FileReader(path));
				
			//3.获取属性,赋值
			url = pro.getProperty("url");
			user = pro.getProperty("user");
			password = pro.getProperty("password");
			driver = pro.getProperty("driver");
			
			//4.注册驱动
			Class.forName(driver);
			
			
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}
		
	}
	

	/**
	 * 获取连接
	 * @return 连接对象
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException {
    
    
		return DriverManager.getConnection(url,user,password);
	}
	
	
	/**
	 * 释放资源
	 * @param stmt
	 * @param conn
	 */
	public static void close(Statement stmt, Connection conn) {
    
    
		if(stmt != null) {
    
    
			try {
    
    
				stmt.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		}
		if(conn != null) {
    
    
			try {
    
    
				conn.close();
			} catch (SQLException e) {
    
    
				e.printStackTrace();
			}
		} 
	}
	
	public static void close(ResultSet rs,Statement stmt, Connection conn) {
    
    
		if(rs != null) {
    
    
			try {
    
    
				rs.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();
			}
		} 
	}
}


编写Properties文件,名称为jdbc.properties

url = jdbc:mysql://localhost/dbTest
user = root
password = root
driver = com.mysql.cj.jdbc.Driver

猜你喜欢

转载自blog.csdn.net/qq_44723773/article/details/110478237