JDBC封装

//JDBC的封装
import java.io.IOException;
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 DBUtil {
	private static String url=null;
	private static String user=null;
	private static String password=null;
	static {
		Properties properties = new Properties();
		try {
			properties.load(DBUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
			 String driver = properties.getProperty("driver");
			 url = properties.getProperty("url");
			 user = properties.getProperty("user");
			 password = properties.getProperty("password");
			 Class.forName(driver);
		
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {	
			e.printStackTrace();
		}
	}
	public static Connection getConn() {
		Connection conn =null;
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void close(ResultSet rs,Statement stm,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(stm!=null) {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

//dbconfig.properties 配置文件

driver =com.mysql.jdbc.Driver
url =jdbc:mysql://localhost:3306/javaee1906
user=root
password=123789
posted @ 2019-08-02 19:09  键盘敲坏  阅读(98)  评论(0编辑  收藏  举报