Second, get a database connection

Second, get a database connection

2.1 Element 1: Driver interface implementation class

2.1.1 Driver interface introduction

Drive network disk address:

  • The java.sql.Driver interface is the interface that all JDBC drivers need to implement. This interface is provided to database vendors, and different database vendors provide different implementations.

  • It is not necessary to directly access the class that implements the Driver interface in the program, but the driver manager class (java.sql.DriverManager) calls these Driver implementations.

    • Oracle的驱动:oracle.jdbc.driver.OracleDriver
    • MySql driver: com.mysql.jdbc.Driver
  • Copy the driver jar package to a directory of the Java project, and it is customary to create a new lib folder.

Note: If it is Dynamic Web Project (dynamic web project), it is necessary to put the driver jar in the lib directory of the WEB-INF directory in the WebContent (some development tools are called WebRoot) directory.

2.1.2 Load and register JDBC driver

  • Load driver: To load the JDBC driver, you need to call the static method forName () of the Class class, passing it the class name of the JDBC driver to be loaded

    • Class.forName(“com.mysql.jdbc.Driver”);
  • Register driver: DriverManager class is driver manager class, responsible for driver management

    • Use DriverManager.registerDriver (com.mysql.jdbc.Driver) to register the driver

    • Usually not explicitly call registerDriver DriverManager class () method to register to the class driver instance, because the driver class Driver interface are included static block of code, static code block in this, calls DriverManager.registerDriver () method Register an instance of itself. The following figure is the source code of MySQL Driver implementation class:

2.2 Element 2: URL

  • The JDBC URL is used to identify a registered driver. The driver manager uses this URL to select the correct driver to establish a connection to the database.

  • The JDBC URL standard consists of three parts, each part separated by a colon.

    • jdbc: subprotocol: subname
    • 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 to identify the database. The sub-name can be changed according to different sub-protocols. The purpose of using the sub-name is to provide sufficient information to locate the database . Contains the host name (corresponding to the IP address of the server) , port number, database name
  • Examples:

  • JDBC URL of several commonly used databases

    • How to write MySQL connection URL:

      • jdbc: mysql: // host name: mysql service port number / database name? parameter = value & parameter = value
      • jdbc:mysql://localhost:3306/xiaoran
      • jdbc: mysql: // localhost: 3306 / xiaoran ? useUnicode = true & characterEncoding = utf8 (If the JDBC program and the server-side character set are inconsistent, it will result in garbled characters, then you can specify the server-side character set through parameters)
      • jdbc:mysql://localhost:3306/xiaoran?user=root&password=123456
    • How to write the connection URL of Oracle 9i:

      • jdbc: oracle: thin: @host name: oracle service port number: database name
      • jdbc:oracle:thin:@localhost:1521:xiaoran
    • SQLServer connection URL writing method:

      • jdbc: sqlserver: // host name: sqlserver service port number: DatabaseName = database name

      • jdbc:sqlserver://localhost:1433:DatabaseName=xiaoran

2.3 Element 3: User name and password

  • user, password can tell the database with "attribute name = attribute value"
  • You can call the getConnection () method of the DriverManager class to establish a connection to the database

2.4 Examples of database connection methods

2.4.1 Connection method 1

	@Test
    public void testConnection1() {
        try {
            //1.提供java.sql.Driver接口实现类的对象
            Driver driver = null;
            driver = new com.mysql.jdbc.Driver();

            //2.提供url,指明具体操作的数据
            String url = "jdbc:mysql://localhost:3306/school";

            //3.提供Properties的对象,指明用户名和密码
            Properties info = new Properties();
            info.setProperty("user", "root");
            info.setProperty("password", "abc123");

            //4.调用driver的connect(),获取连接
            Connection conn = driver.connect(url, info);
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

Note: The API of the third-party database appears explicitly in the above code

2.4.2 Connection method 2

	@Test
    public void testConnection2() {
        try {
            //1.实例化Driver
            String className = "com.mysql.jdbc.Driver";
            Class clazz = Class.forName(className);
            Driver driver = (Driver) clazz.newInstance();

            //2.提供url,指明具体操作的数据
            String url = "jdbc:mysql://localhost:3306/school";

            //3.提供Properties的对象,指明用户名和密码
            Properties info = new Properties();
            info.setProperty("user", "root");
            info.setProperty("password", "abc123");

            //4.调用driver的connect(),获取连接
            Connection conn = driver.connect(url, info);
            System.out.println(conn);

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

Note: Compared to the first method, Driver is used to instantiate Driver instead of reflecting the API of the third-party database in the code. Reflects the idea of ​​interface-oriented programming.

2.4.3 Connection Mode 3

	@Test
    public void testConnection3() {
        try {
            //1.数据库连接的4个基本要素:
            String url = "jdbc:mysql://localhost:3306/school";
            String user = "root";
            String password = "abc123";
            String driverName = "com.mysql.jdbc.Driver";

            //2.实例化Driver
            Class clazz = Class.forName(driverName);
            Driver driver = (Driver) clazz.newInstance();
            //3.注册驱动
            DriverManager.registerDriver(driver);
            //4.获取连接
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Note: Use DriverManager to connect to the database.

2.4.4 Connection method 4

	@Test
    public void testConnection4() {
        try {
            //1.数据库连接的4个基本要素:
            String url = "jdbc:mysql://localhost:3306/school";
            String user = "root";
            String password = "abc123";
            String driverName = "com.mysql.jdbc.Driver";

            //2.加载驱动 (①实例化Driver ②注册驱动)
            Class.forName(driverName);

            /*
            在mysql的Driver类中声明有这样的静态方法:
            static {
                try {
                    DriverManager.registerDriver(new Driver());
                } catch (SQLException var1) {
                    throw new RuntimeException("Can't register driver!");
                }
            }
             */


            //3.获取连接
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Note: There is no need to explicitly register the driver. Because the static code block already exists in the source code of the Driver class, the registration of the driver is realized.

2.4.5 Connection Mode 5 (Final Version)

    @Test
    public void testConnection5() throws Exception {
        //1.加载配置文件
        InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);

        //2.读取配置文件
        String url = pros.getProperty("url");
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String dirverClass = pros.getProperty("driverClass");

        //3.加载驱动
        Class.forName(dirverClass);

        //4.获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

Among them, the configuration file is declared in the src directory of the project: [jdbc.properties]

user=root
password=123456
url=jdbc:mysql://localhost:3306/school
driverClass=com.mysql.jdbc.Driver

Description: Use the configuration file to save the configuration information and load the configuration file in the code

Benefits of using configuration files:

① Separation of code and data is realized. If configuration information needs to be modified, modify it directly in the configuration file without in-depth code.
② If configuration information is modified, the process of recompilation is omitted.

Guess you like

Origin www.cnblogs.com/xiaoran991/p/12725119.html