A Java utility class that connects to a Mysql database
- 2020-04-01 03:45:09
- OfStack
An encapsulated link to the Mysql database utility class, you can easily get Connection objects close Statement, ResultSet, Statment objects, and so on
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 mysql The 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! ");
}
}
/**
* To obtain 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(" Failed to get database connection! ");
throw e;
}
return conn;
}
/**
* Shut down ResultSet
* @param rs
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
/**
* Shut down Statement
* @param stmt
*/
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
/**
* Shut down ResultSet , Statement
* @param rs
* @param stmt
*/
public static void closeStatement(ResultSet rs, Statement stmt) {
closeResultSet(rs);
closeStatement(stmt);
}
/**
* Shut down PreparedStatement
* @param pstmt
* @throws SQLException
*/
public static void fastcloseStmt(PreparedStatement pstmt) throws SQLException
{
pstmt.close();
}
/**
* Shut down ResultSet , PreparedStatement
* @param rs
* @param pstmt
* @throws SQLException
*/
public static void fastcloseStmt(ResultSet rs, PreparedStatement pstmt) throws SQLException
{
rs.close();
pstmt.close();
}
/**
* Shut down 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);
}
/**
* Shut down Statement , Connection
* @param stmt
* @param con
*/
public static void closeConnection(Statement stmt, Connection con) {
closeStatement(stmt);
closeConnection(con);
}
/**
* Shut down 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 the entire content of this article, hope to help you master Java.