Copy the code code as follows:
package sns.team6.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Tool class for linking to database
*
* @author Xu Rui
*
*/
public class DBHelper {
// mysql driver path
private static final String driver = "com.mysql.jdbc.Driver";
//Database connection path
private static final String url = "jdbc:mysql://localhost:3306/snsteam6";
/**
* Object to connect to the database
*
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "root", "root");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* Close the open resource
*
* @param conn
* @param pst
* @param rst
*/
public static void closeInfo(Connection conn, PreparedStatement pst,
ResultSet rst) {
try {
if (rst != null) {
rst.close();
rst = null;
}
if (pst != null) {
pst.close();
pst = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the result set object
*
* @param sql
* @param params
* @return
*/
public static ResultSet resultSet(String sql, Object[] params) {
//Database link object
Connection conn = null;
//Database operation object
PreparedStatement pst = null;
// result object
ResultSet rst = null;
try {
//Database link object
conn = DBHelper.getConnection();
//Database operation object
pst = conn.prepareStatement(sql);
// Determine whether there are parameters
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
//Assign a value to the operation object
pst.setObject(i + 1, params[i]);
}
}
// Get the result object
rst = pst.executeQuery();
} catch (SQLException e) {
rst = null;
e.printStackTrace();
}
return rst;
}
/**
* Get the added result object
*
* @param sql
* @param params
* @return
*/
public static boolean result(String sql, Object[] params) {
boolean flag = false;
//Database link object
Connection conn = null;
//Database operation object
PreparedStatement pst = null;
try {
//Database link object
conn = DBHelper.getConnection();
//Database operation object
pst = conn.prepareStatement(sql);
// Determine whether there are parameters
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
//Assign a value to the operation object
pst.setObject(i + 1, params[i]);
}
}
// Get the result object, which is of type int, indicating the number of rows successfully executed.
int row = pst.executeUpdate();
if (row > 0) {
// If it is greater than 0, it means the execution is successful
flag = true;
}
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
return flag;
}
}