跟汤老师学Java笔记:封装JdbcUtil工具类

跟汤老师学Java笔记:封装JdbcUtil工具类

完成:第一遍

1.如何封装JdbcUtil工具类?

静态方法:获取数据库连接 getConnection()

静态方法:关闭资源close(connection,statement,resultSet)

静态方法:重载关闭资源close(connection,statement)

package code19_JDBC;

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

/**
 * JDBC工具类
 */
public class JdbcUtil {
	/**
	 * 获取数据库连接
	 */
	public static Connection getConnection() {
		String driverClassName = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true";
		String username = "root";
		String password = "";

		Connection conn = null;
		try {
			Class.forName(driverClassName);
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭资源,关闭connection,statement,resultSet
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		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();
			}
		}
	}

	/**
	 * 重载关闭资源方法,关闭connection,statement
	 */
	public static void close(Connection conn, Statement stmt) {
		close(conn, stmt, null);
	}
}

你可能感兴趣的:(Java之JDBC数据库连接,jdbc)