Get database connection

Posted by pbsonawane on Wed, 09 Feb 2022 12:02:12 +0100

1, Element 1: Driver interface implementation class

1. Introduction to driver interface

  • java.sql.Driver interface is the interface that all JDBC drivers need to implement. This interface is provided for database manufacturers. Different database manufacturers provide different implementations
  • Instead of directly accessing the classes that implement the Driver interface in the program, the Driver manager class (java.sql.DriverManager) calls these Driver implementations
    • Oracle driver: Oracle jdbc. driver. OracleDriver
    • MySQL driver: com mysql. cj. jdbc. Driver

After specifying the driver, MySQL needs to load its driver jar package

  • ① It is customary to create a new lib folder
  • ② Copy the jar package to the lib directory of the Java project
  • ③ Right click - > Add as library
  • ④ Open Project Structure and bind jar package



2 load and register JDBC Driver

  • Load driver: to load the JDBC driver, you need to call the static method forName() of Class class and pass the Class name of the JDBC driver to be loaded Class forName(“com.mysql.cj.jdbc.Driver”)
  • Register driver: DriverManager class is the driver manager class, which is responsible for managing drivers
    • Using drivermanager Register driver (COM. Mysql. CJ. JDBC. Driver) to register the driver
    • Usually, you don't need to explicitly call the registerDriver() method of the DriverManager class to register an instance of the Driver class, because the Driver classes of the Driver interface contain static code blocks in which DriverManager will be called registerDriver() method to register an instance of itself. The following is the source code of the Driver implementation class of MySQL:
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

2, Element 2: URL

JDBC URL is used to identify a registered driver. The driver manager selects the correct driver through this URL to establish a connection to the database
The standard JDBC URL consists of three parts separated by colons

jdbc: sub protocol: sub name
-Protocol: the protocol in the JDBC URL is always jdbc

  • Sub protocol: the sub protocol is used to identify a database driver
  • Subname: a method of identifying a database. The sub name can be changed according to different sub protocols. The purpose of using the sub name is to provide sufficient information for locating the database. Including host name (corresponding to the ip address of the server), port number and database name

3, Element 3: user name and password

User and password can tell the database in the way of "attribute name = attribute value"
You can call the getConnection() method of the DriverManager class to establish a connection to the database

4, Example of database connection mode

The five ways are iterative relationship, and the fifth way is the final version

1. Connection mode I

@Test
public void testConnection1() throws SQLException {
    //1. Get the implementation class object of Driver
    Driver driver = new com.mysql.cj.jdbc.Driver();
    //2. Provide the database to be connected
    String url = "jdbc:mysql://localhost:3306/test";
    //3. Provide the user name and password required for connection
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","mg123456");
    //4. Get connection
    Connection conn = driver.connect(url,info);
    System.out.println(conn);
}

java program is interface oriented programming. I hope it has better portability. There should be no third-party api in the code as far as possible. com.mysql.cj.jdbc.Driver() is a third-party api, so we don't want it to appear in this way. How do we get the driver implementation class object of MySQL—— reflex
Through reflection, we can better package it and realize dynamic acquisition; When it comes to reflection, we should think of its dynamic nature. Since the connection of which database we want to obtain is uncertain at first, now we use mysql database, so we obtain it in the form of string

2 connection mode II

//Method 2: no third-party api
@Test
public void testConnection2() throws Exception {
    //1. Get the implementation class object of Driver: Reflection implementation
    Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    //2. Provide the database to be connected
    String url = "jdbc:mysql://localhost:3306/test";
    //3. Provide the user name and password required for connection
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","mg123456");
    //4. Get connection
    Connection conn = driver.connect(url,info);
    System.out.println(conn);
}

3 connection mode III

//Method 3: replace Driver with Driver manager
@Test
public void testConnection3() throws Exception {
    //1. Get the implementation class object of Driver
    Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    //2. Provide the other three basic information for obtaining connections
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "mg123456";
    //Register driver
    DriverManager.registerDriver(driver);
    //Get connection
    Connection conn = DriverManager.getConnection(url, user, password);
    System.out.println(conn);
}

4 connection mode IV

//Method 4: just load the driver, not display the registered driver
@Test
public void testConnection4() throws Exception {
    //1. Provide three basic information for obtaining connection
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "mg123456";

    //2. Load Driver
    Class.forName("com.mysql.cj.jdbc.Driver");//Load mysql classes into memory
//        Driver driver = (Driver) clazz.newInstance();
//        //Register driver
//        DriverManager.registerDriver(driver);

    //3. Get connection
    Connection conn = DriverManager.getConnection(url, user, password);
    System.out.println(conn);
}


The Driver needs to be registered, but there is no problem deleting it. mysql can only help us register the Driver. The following operations are declared in the Driver implementation class of mysql:

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

There is a static code block in the Driver. The static code block is executed when the class is loaded. Therefore, when the mysql class is loaded, the static method is executed to help us register the Driver and new the Driver's implementation class object

5 connection mode V (final version)

//Method 5: in the final version, declare the four basic information required for database connection in the configuration file, and obtain the connection by reading the configuration file
@Test
public void testConnection5() throws Exception {
    //1. Read the four basic information in the configuration file
    InputStream is = connection_Test.class.getClassLoader().getResourceAsStream("jdbc.properties");

    Properties pros = new Properties();
    pros.load(is);

    String user = pros.getProperty("user");
    String password = pros.getProperty("password");
    String url = pros.getProperty("url");
    String driverClass = pros.getProperty("driverClass");

    //2. Load drive
    Class.forName(driverClass);

    //3. Get connection
    Connection conn = DriverManager.getConnection(url, user, password);
    System.out.println(conn);
}

Benefits of this approach:

  1. It realizes the separation of data and code and decoupling
  2. If you need to modify the configuration file information, you can avoid repackaging the program

Topics: JDBC