A packaged tool class that links Mysql databases can easily obtain Connection objects to close Statement, ResultSet, Statment objects, etc.
The code copy is as follows:
package myUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Link to mysql database
* @author weichk
*/
public class MysqlDbManager {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/openfire";
private static final String USER = "root";
private static final String PASSWORD = "123456";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Loading Mysql database driver failed!");
}
}
/**
* Get Connection
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
System.out.println("Get database connection failed!");
throw e;
}
return conn;
}
/**
* Close ResultSet
* @param rs
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
/**
* Close Statement
* @param stmt
*/
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
/**
* Close ResultSet, Statement
* @param rs
* @param stmt
*/
public static void closeStatement(ResultSet rs, Statement stmt) {
closeResultSet(rs);
closeStatement(stmt);
}
/**
* Close PreparedStatement
* @param pstmt
* @throws SQLException
*/
public static void fastcloseStmt(PreparedStatement pstmt) throws SQLException
{
pstmt.close();
}
/**
* Close ResultSet, PreparedStatement
* @param rs
* @param pstmt
* @throws SQLException
*/
public static void fastcloseStmt(ResultSet rs, PreparedStatement pstmt) throws SQLException
{
rs.close();
pstmt.close();
}
/**
* Close ResultSet, Statement, Connection
* @param rs
* @param stmt
* @param con
*/
public static void closeConnection(ResultSet rs, Statement stmt, Connection con) {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
/**
* Close Statement, Connection
* @param stmt
* @param con
*/
public static void closeConnection(Statement stmt, Connection con) {
closeStatement(stmt);
closeConnection(con);
}
/**
* Close Connection
* @param con
*/
public static void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
The above is all about this article. I hope it will be helpful for everyone to master Java proficiently.