Java gets the implementation code for the database connection

  • 2020-04-01 02:02:49
  • OfStack

The code is as follows:



package com.cai.jdbc;
import java.sql.Connection; 
import java.sql.DriverManager;
import java.util.Properties ;
public class ConnectionUtil {
 
 public Connection getConnection(){
  Connection conn = null ;
  try{
   Class.forName("com.mysql.jdbc.Driver") ;

   conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stud", "root", "root") ;

   return conn ;

  }catch(Exception e){
   e.printStackTrace() ;
  }
  return null ;
 }

 
 public Connection getConnection(String driver, String url, String user, String password){

  Connection conn = null ;

  try{
   Class.forName(driver) ;
   conn = DriverManager.getConnection(url, user, password) ;

   return conn ;

  }catch(Exception e){
   e.printStackTrace();
  }

  return null ;
 }

 
 public Connection openConnection(){

  Connection conn = null ;
  String driver   = "" ;
  String url      = "" ;
  String user     = "" ;
  String password = "" ;
  Properties props = new Properties() ;
  try{
   props.load(this.getClass().getClassLoader().getResourceAsStream("DBConfig.properties")) ;
   driver   = props.getProperty("driver") ;
   url      = props.getProperty("url") ;
   user     = props.getProperty("user") ;
   password = props.getProperty("password") ;

   Class.forName(driver) ;
   conn = DriverManager.getConnection(url, user, password) ;

   return conn ;
  }catch(Exception e){
   e.printStackTrace() ;
  }

  return null ;
 }

 public static void main(String []args){
  ConnectionUtil cu = new ConnectionUtil() ;

  System.out.println("1 , ---->" + cu.getConnection()) ;
  System.out.println("2 , ---->" + cu.getConnection("com.mysql.jdbc.Driver", 
    "jdbc:mysql://localhost:3306/stud", "root", "root")) ;
  System.out.println("3 , ---->" + cu.openConnection()) ;

 }

 
}

Related articles: