Java tip [012]: Why class. forname ("") is used for JDBC development?

Source: Internet
Author: User
Tags finally block

A few days ago I saw a post asking a question. Why should I use class. forname in JDBC development?

Let's start with the code to analyze this problem.

The following is a piece of common JDBC development code (Note: MySQL is used as an example in this article. For ease of demonstration, ignore exception handling in the Code)

Class. forname ("com. mySQL. JDBC. driver "); <br/> conn = drivermanager. getconnection (<br/> "JDBC: mysql: // localhost: 3306/MySQL", "root", ""); <br/> stmt = Conn. createstatement (); <br/> rs = stmt.exe cutequery ("select count (0) from user"); <br/> while (RS! = NULL & Rs. Next () {<br/> system. Out. println (Rs. getint (1); <br/>}

Run the code and the result is normal. The number of users in the MySQL database is printed.

Let's remove the first sentence first to see if it can run.

// Remove the class. forname statement. Check the running result. <br/> // class. forname ("com. mySQL. JDBC. driver "); <br/> conn = drivermanager. getconnection (<br/> "JDBC: mysql: // localhost: 3306/MySQL", "root", ""); <br/> stmt = Conn. createstatement (); <br/> rs = stmt.exe cutequery ("select count (0) from user"); <br/> while (RS! = NULL & Rs. Next () {<br/> system. Out. println (Rs. getint (1); <br/>}

Run the code and report the following error:

Java. SQL. sqlexception: no suitable driver found for JDBC: mysql: // localhost: 3306/MySQL <br/> at java. SQL. drivermanager. getconnection (drivermanager. java: 602) <br/> at java. SQL. drivermanager. getconnection (drivermanager. java: 185) <br/> at net. moon. JDBC. demo. demo. main (demo. java: 18)

It seems that this is not the case. Let's analyze what the class. forname (string clz) method has done?

Let's take a look at the API. The class. forname method declaration in the API is as follows:

Public static class <?> Forname (string classname) <br/> throws classnotfoundexception

This method obtains the class represented by this string based on a string. However, no reference in the code above points to the returned result, that is, the Code does not focus on the returned result, then, why do we need to execute this sentence? Let's continue to look at the descriptions in the API and see the following: "A CallForname ("X ")Causes the class namedXTo be initialized ".

The problem seems to be a little eye-catching, and the class is being executed. forname ("com. mySQL. JDBC. driver "), Com. mySQL. JDBC. the driver class is initialized, which must be the action in initialization. To verify this, we have made some changes to the above Code:

// Class. forname ("com. mySQL. JDBC. driver "); <br/> // create a driver object, and do not pay attention to the returned results. <br/> new COM. mySQL. JDBC. driver (); <br/> conn = drivermanager. getconnection (<br/> "JDBC: mysql: // localhost: 3306/MySQL", "root", ""); <br/> stmt = Conn. createstatement (); <br/> rs = stmt.exe cutequery ("select count (0) from user"); <br/> while (RS! = NULL & Rs. Next () {<br/> system. Out. println (Rs. getint (1); <br/>}

Run the code, as expected, and get the running result.

Let's take a look at what the com. MySQL. JDBC. Driver Class executes during initialization? Let's recall a previous article: Java horn tip [003]: The execution sequence of class initialization. It seems that there is a concept: static code block.

It must have a static code segment in the com. MySQL. JDBC. Driver Class. This Code executes some actions.

Another advantage of using MySQL as an example is that it is open-source, which means we can see its code, so the next task is to find COM. mySQL. JDBC. let's take a look at the source code of the driver class.

The Code is as follows:

Static {<br/> try {<br/> JAVA. SQL. drivermanager. registerdriver (New Driver (); <br/>} catch (sqlexception e) {<br/> throw new runtimeexception ("can't register driver! "); <Br/>}< br/>}

This Code seems simpler than we thought. It is to register the JDBC driver through the static method registerdriver of the Java. SQL. drivermanager class.

The last question is why the registerdriver method is called here. Let's take a look at the drviermanager API, as shown below:

Registerdriver <br/> Public static void registerdriver (driver Driver) <br/> throws sqlexception </P> <p> registers a given driver with drivermanager. The newly loaded Driver Class should call the registerdriver method to let drivermanager know itself. </P> <p> parameter: <br/> driver-a new JDBC driver registered with drivermanager is thrown: <br/>: <br/> sqlexception-if a database access error occurs

 

Previous Article: Java tip [011]: Does Java support single inheritance only?

Next article: Java tip [013]: will the code in the Finally block be executed?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.