Learn the example of Java connection to mysql database

  • 2020-04-01 03:11:08
  • OfStack


package sns.team6.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBHelper {
 //Mysql driver path
 private static final String driver = "com.mysql.jdbc.Driver";
 //The connection path to the database
 private static final String url = "jdbc:mysql://localhost:3306/snsteam6";
 
 public static Connection getConnection() {
  Connection conn = null;
  try {
   Class.forName(driver);
   conn = DriverManager.getConnection(url, "root", "root");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
 
 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();
  }
 }
 
 public static ResultSet resultSet(String sql, Object[] params) {
  //The linked object of the database
  Connection conn = null;
  //The operation object of the database
  PreparedStatement pst = null;
  //The result object
  ResultSet rst = null;
  try {
   //The linked object of the database
   conn = DBHelper.getConnection();
   //The operation object of the database
   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 action object
     pst.setObject(i + 1, params[i]);
    }
   }
   //Get the result object
   rst = pst.executeQuery();
  } catch (SQLException e) {
   rst = null;
   e.printStackTrace();
  }
  return rst;
 }
 
 public static boolean result(String sql, Object[] params) {
  boolean flag = false;
  //The linked object of the database
  Connection conn = null;
  //The operation object of the database
  PreparedStatement pst = null;
  try {
   //The linked object of the database
   conn = DBHelper.getConnection();
   //The operation object of the database
   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 action object
     pst.setObject(i + 1, params[i]);
    }
   }
   //Get the result object, is int Type representing the number of successful rows 
   int row = pst.executeUpdate();
   if (row > 0) {
    //If it's greater than 0, it's a success
    flag = true;
   }
  } catch (SQLException e) {
   flag = false;
   e.printStackTrace();
  }
  return flag;
 }
}


Related articles: