JdbcUtil

package com.itheima.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
//通用的工具类:与具体数据库没有关系
public class JdbcUtil {
	
	private static String driverClass;
	private static String url;
	private static String username;
	private static String password;
	
	
	static{
		try {
			//加载配置文件
			InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbcfg.properties");
			Properties props = new Properties();
			props.load(in);
			
			driverClass = props.getProperty("driverClass");
			url = props.getProperty("url");
			username = props.getProperty("username");
			password = props.getProperty("password");
			
			Class.forName(driverClass);
			
			
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	//获取数据库的连接
	public static Connection getConnection() throws Exception{
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}
	//释放占用的资源
	public static void release(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();
			}
		}
	}
}

阅读更多
换一批

没有更多推荐了,返回首页