Home  >  Article  >  Java  >  How to encapsulate JDBC tool class in Java?

How to encapsulate JDBC tool class in Java?

PHPz
PHPzforward
2023-04-22 08:34:061243browse

1. Description

In the java development process, some classes like Scanner and Random are often used in the code. They are classes for keyboard input and random number generation, like a Like tools, they are called tool classes in Java.

2. Steps

Encapsulate the JDBC tool class

Add a method to obtain the database connection object

Add a method to release the connection

3. Example

package com.qianfeng.util;
 
 
 
import java.sql.Connection;
 
import java.sql.DriverManager;
 
import java.sql.ResultSet;
 
import java.sql.SQLException;
 
import java.sql.Statement;
 
 
 
/**
 
 * JDBC工具类
 
 * 有获取连接的方法
 
 * @author dushine
 
 */
 
public class JDBCUtil {
 
 
 
/**
 
 * 获取数据库连接的方法
 
 * @return Connection conn
 
 * @throws SQLException
 
 */
 
public static Connection getConnection() throws SQLException {
 
String url = "jdbc:mysql://localhost:3306/class?useSSL=false";
 
String user = "root";
 
String password = "root";
 
Connection conn = DriverManager.getConnection(url,user,password);
 
return conn;
 
}
 
 
 
/**
 
 * 释放连接的方法
 
 * @param conn
 
 * @throws SQLException
 
 */
 
public static void releaseSourse(Connection conn) throws SQLException {
 
if (conn != null) {
 
conn.close();
 
}
 
}
 
 
 
 
 
/**
 
 * 释放连接的方法
 
 * @param conn 数据库连接对象
 
 * @param stmt 执行SQL语句的对象
 
 * @throws SQLException
 
 */
 
public static void releaseSourse(Connection conn,Statement stmt) throws SQLException {
 
if (stmt != null) {
 
stmt.close();
 
}
 
 
 
if (conn != null) {
 
conn.close();
 
}
 
}
 
 
 
/**
 
 * 释放连接的方法
 
 * @param conn 数据库连接对象
 
 * @param stmt 执行SQL语句的对象
 
 * @param resultSet 执行SQL语句的返回的结果集
 
 * @throws SQLException
 
 */
 
public static void releaseSourse(Connection conn,Statement stmt,ResultSet resultSet) throws SQLException {
 
if (resultSet != null) {
 
resultSet.close();
 
}
 
 
 
if (stmt != null) {
 
stmt.close();
 
}
 
 
 
if (conn != null) {
 
conn.close();
 
}
 
}
 
}

The above is the detailed content of How to encapsulate JDBC tool class in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete