Upgrade the JDBC driver to Version 8.0.28 to connect to the pit record of MySQL

πŸ‘²πŸ‘² Author home page: πŸ”— Jason's blog πŸ“’πŸ“’ Abstract of this article: considerations for upgrading the driver to MySQL connector Java 8.0.28

Article directory

πŸ› Problem description

After upgrading the driver to MySQL connector Java 8.0.28, various errors are reported during deployment, but there is no problem switching the connector to MySQL connector Java 5.1.48. I am very confused!

Most of the error messages are unable to find or connect

The main thing is that after the configuration is completed, no screenshots are left. Just pay attention to the differences between the old version and the old version

Official download address

After all kinds of difficulties and obstacles, it is finally solved. The connection is successful. The solution is given below

πŸ’‘ Solution

The first is the example of a rookie, which is more comprehensive; If you feel troublesome, you can use the second scheme

one πŸ”Ž Full version

Here is an example of a rookie tutorial

πŸ“‘ 1. database environment construction

-- set up a database demo1
CREATE DATABASE IF NOT EXISTS demo1;

-- establish websites surface
CREATE TABLE websites (
  id int(11) NOT NULL AUTO_INCREMENT,
  name char(20) NOT NULL DEFAULT '' COMMENT 'Site name',
  url varchar(255) NOT NULL DEFAULT '',
  alexa int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa ranking',
  country char(10) NOT NULL DEFAULT '' COMMENT 'country',
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- Write data
INSERT INTO websites
VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), 
('2', 'TaoBao', 'https://www.taobao.com/', '13', 'CN'), 
('3', 'Rookie tutorial', 'http://www.runoob.com', '5892', ''), 
('4', 'micro-blog', 'http://weibo.com/', '20', 'CN'), 
('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA');
copy

πŸ“‘ 2. test connection

The most important issue here is the MySQL version. The new version updates the name of the driver class to com mysql. cj. jdbc. Driver

import java.sql.*;

public class JDBCTest {

    // MySQL versions below 8.0 - JDBC driver name and database URL
    // static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    // static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";

    // MySQL 8.0 or above - JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/demo1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useServerPrepStmts=true";
                                                            // Pay attention to modifying the database name 

    // The user name and password of the database should be set according to your own settings
    static final String USER = "your db login name";
    static final String PASS = "your db password";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // Register JDBC Driver
            Class.forName(JDBC_DRIVER);

            // Open link
            System.out.println("Connect to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Execute query
            System.out.println(" instantiation  Statement object...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);

            // Expand result set database
            while (rs.next()) {
                // Retrieve by field
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");

                // output data
                System.out.print("ID: " + id);
                System.out.print(", Site name: " + name);
                System.out.print(", site URL: " + url);
                System.out.print("\n");
            }
            // Close on completion
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // Handling JDBC errors
            se.printStackTrace();
        } catch (Exception e) {
            // Process class Forname error
            e.printStackTrace();
        } finally {
            // close resource
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }// Don't do anything?
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}
copy

Execution result, connection successful

two πŸ”Ž Lite

The above example is comprehensive and uses many exceptions. To facilitate understanding, let's simplify the code quantity

πŸ“‘ 1. database environment construction

-- set up a database demo1
CREATE DATABASE IF NOT EXISTS demo1;

-- Create data table accounts
CREATE TABLE accounts (
			id int(3) NOT NULL PRIMARY KEY auto_increment,
			name varchar(5),
			money FLOAT(4,2)
			);

-- Write data
INSERT INTO accounts VALUES('1','jason','10000'),('2','you','99999');
copy

πŸ“‘ 2. test connection

Pay attention to the release order of versions and resources (call first and release last, and the release order is opposite to the call order)

package com.jason.jdbc;

import java.sql.*;

public class JDBCDemo {
    public static void main(String[] args) throws Exception { //psvm fast generation
        //1. register driver
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2. get connection
        String url = "jdbc:mysql://localhost:3306/demo1?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useServerPrepStmts=true";
        String username = "your db login name";
        String password = "your db password";
        Connection conn = DriverManager.getConnection(url, username, password);
        //3. define sql
        String sql = "update accounts set money = 1000 where id = 2";
        //4. get the object Statement executing sql
        Statement stmt = conn.createStatement();
        //5. execute sql
        int count = stmt.executeUpdate(sql);//Number of rows affected
        //6. treatment results
        System.out.println("Affected rows: "+count);
        //7. release the resource Statement and Connection. Pay attention to the release order
        stmt.close();
        conn.close();
    }
}
copy

Execution result, connection successful

πŸ“’ summary

After all, it is an update. There will be some changes. We need to learn to see what has been updated and to find official solutions

For example, this error can be found in the latest jar package

In 5 After the X version, the code for registering the driver can be omitted. This is the paragraph

//1. register driver
//Class.forName("com.mysql.cj.jdbc.Driver");
copy

The reason is: under the driver jar package, the corresponding driver class name is recorded in the default META-INF services directory, so it is unnecessary to write it again

Maybe the version I use is too old to keep up with the development of the times~~

Posted by luanne on Fri, 03 Jun 2022 10:31:20 +0530