Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis on the need to add Class.forName (& quot;com.mysql.jdbc.Driver") to operate MySQL with JDBC

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Introduction

If you are familiar with using JDBC to connect to the database, you must know that there must be some Class.forName in the code to connect to the database.

("com.mysql.jdbc.Driver"); public static Connection getConnection () throws ClassNotFoundException, SQLException {if (connection = = null) {Class.forName ("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC", "root", "xxxxxx");} return connection;}

I have never thought about why there is such a statement, which is done directly according to the document. In this article, I will try to explain the reason for doing so.

Class loading mechanism

Before we do that, let's talk about the class loading mechanism in Java.

If you want to use a class in Java, you must require that the class has been loaded into the Jvm. The loading process is actually to get the binary byte stream that defines the class through the fully qualified name of the class, and then convert the static storage structure represented by the byte stream into the dynamic runtime data structure represented by the method. At the same time, instantiate a java.lang.Class object in memory as the data access entry for this class in the method area (for us to use).

There are several situations that trigger class loading (quoted from):

1. When you encounter four bytecode instructions: new, getstatic, putstatic, or invokestatic, if the class has not been initialized, you need to trigger its initialization first. The most common Java code scenarios that generate these four instructions are when an object is instantiated with the new keyword, when a static field of a class is read or set (except for a static field that has been decorated by final and the result has been put into a constant pool at compile time), and when a class's static method is called.

two。 When you make a reflection call to a class using the method of the java.lang.reflect package, if the class has not been initialized, you need to trigger its initialization first.

3. When initializing a class, if you find that its parent class has not been initialized, you need to trigger the initialization of its parent class first.

4. When the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual machine initializes the main class first.

Class.forName

Class.forName is interpreted in the Java official documentation as dynamically loading a class at run time, and the return value is the generated Class object.

So it's obvious that you use Class.forName ("com.mysql.jdbc.Driver") in jdbc; you just load the com.mysql.jdbc.Driver class into Jvm, a reason that most people should know.

But we need to know that Class.forName seems to just load the class, and we didn't even do anything on the returned Class object, so why can we just use it later?

First of all, Class.forName calls the native method forName0 (...).

@ CallerSensitivepublic static Class forName (String className) throws ClassNotFoundException {Class caller = Reflection.getCallerClass (); return forName0 (className, true, ClassLoader.getClassLoader (caller), caller);} private static native Class forName0 (String name, boolean initialize,ClassLoader loader,Class caller)

Note that there is a key parameter in forName0, boolean initialize,;, which is used to identify whether initialization occurs after the class is loaded. You can see that true is in the code, which means that the initialization operation will take place.

The initialization process is actually the process of assigning a value to a variable (not assigning an initial value and not calling a constructor). Contains the assignment of all class variables and the execution code of static code statement blocks, including initialization of the parent class.

Take a look at the com.mysql.jdbc.Driver driver class:

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!");}

A static code block is defined in this class, a driver class instance is created in the static code and registered with DriverManager, and the contents of the static code block are executed during initialization, so a connection can be obtained directly through DriverManager.getConnection.

Other load class methods

What we need to understand is that there are not loaded classes in Java that can be displayed only through Class.forName (). So why choose Class.forName () instead of using other loading methods?

ClassLoader.getSystemClassLoader () .loadClass ()

A class can also be loaded into Jvm through the class loader. You can also load driver classes through ClassLoader.getSystemClassLoader (). LoadClass ("com.mysql.jdbc.Driver").

But if we take a closer look at the implementation of loadClass:

Public Class loadClass (String name) throws ClassNotFoundException {return loadClass (name, false);} protected Class loadClass (String name, boolean resolve)

You can see that it calls an overloaded method, which also has a variable boolean resolve of type boolean, which defaults to false. This parameter is used to identify whether to link the loaded class, and there will be no initialization if the connection is not performed.

So if you use this way of loading classes, then theoretically speaking, there is no use of this driver class.

New keyword

You can also use the new keyword for the load operation, which checks to see if the class has been loaded when using the new keyword, and loads if not. So we can also write this in our class:

Public static Connection getConnection () throws ClassNotFoundException, SQLException {if (connection = = null) {new Driver (); / / static code block connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC", "root", "xxxx");} return connection;}

But in fact, because you already have the operation to instantiate the object and register it in the DriverMananger in the static code fast that drives the class. So there is no process of instantiating an object at all. Just use Class.forName, which can be regarded as an optimization process.

You don't have to use Class.forName ("com.mysql.jdbc.Driver")

In the course of testing, I found it strange to use Class.forName ("com.mysql.jdbc.Driver") to connect to the database even if it was not shown.

After deeply tracking the code, we found that as long as we introduced the mysql driver package, we would create a class by default according to the configuration file provided under the driver package.

So in fact, as long as the driver package is introduced, the connection can be obtained directly through DriverManage using jdbc.

Public static Connection getConnection () SQLException {return DriverManager.getConnection ("jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC", "root", "xxxxxx");}

Summary

The above is the editor to introduce to you why to use JDBC to operate MySQL need to add Class.forName ("com.mysql.jdbc.Driver"), hope to help you, if you have any questions, please leave me a message, the editor will reply to you in time. Thank you very much for your support to the website!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report