jdbc工具类(辅助类),连接数据库

利用工具类方便使用jdbc

package cn.itcast.jdbc2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class JdbcUtils2 {

	private static final String URL = "jdbc:mysql://localhost:3306/imooc?serverTimezone=UTC ";
	private static final String USER = "root";
	private static final String PASSWORD = "root";
	
	private JdbcUtils2() {
	}
	
	static {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
	
	public static void free(ResultSet rs,Statement stmt,Connection conn) {
		try {
			if(rs!=null)
			rs.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(stmt!=null)
			stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if(conn!=null)
					try {
						conn.close();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		}
	}
}

发布了25 篇原创文章 · 获赞 5 · 访问量 1893

猜你喜欢

转载自blog.csdn.net/DoMyBestintheworld/article/details/103825767