JDBC and mysqljdbc
In the previous article "Let's talk about Java EE", we will explain what norms are and what their functions are. In this article, we will elaborate on JDBC.
JDBC
JDBC (Java Database Connection) is also a specification in Java EE. The so-called specification is a set of interfaces. For example, JDBC interfaces are included in java. SQL and javax. in the SQL package, java. SQL belongs to JavaSE and javax. SQL is a Java EE part, such:
The above is from src/java/SQL in jdk.
Because API-oriented programming is promoted, we recommend that you use only the classes in the JDBC specification. The relationship between the specification and implementation is as follows:
The core APIs in JDBC are as follows:
- DriverManager: factory class used to produce Driver objects
- Driver: interface of the Driver object
- Connection: database Connection object
- Statement: interface for executing static SQL statements
- Resultset: interface of the result set object
Procedure
- Load database driver
- Create a database connection
- Run the SQL statement to obtain the result set.
- Perform CRUD processing on the result set
- Release resources
Source code analysis
There are 48 classes in java. SQL and 45 classes in javax. SQL. The analysis is not realistic. This article only analyzes two classes, DriverManager and Driver. I don't know if you have noticed this problem. JDBC is an interface and database driver is an implementation. How can you find the implementation of your project?
Console output
To view the logs output during Driver loading, add the following statement before loading the Driver Class. forName ("com. mysql. jdbc. Driver:
DriverManager.setLogWriter(new java.io.PrintWriter(System.out));
You can see the output in the console.
Load driver
The driver is easy to use. Put the database driver in the lib of the project and write it into the Code:
Class.forName("com.mysql.jdbc.Driver");If the framework is used, such as writing in the Hebernate configuration file:
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
Obviously, both methods use reflection to load the Driver, let's take a look at the source code of the Driver, take the mysql-connector-java-3.1.13 as an example:
package com.mysql.jdbc;import java.sql.SQLException;public class Driver extends NonRegisteringDriver implements java.sql.Driver {//// Register ourselves with the DriverManager//static {try {java.sql.DriverManager.registerDriver(new Driver());} catch (SQLException E) {throw new RuntimeException("Can't register driver!");}}/** * Construct a new driver and register it with DriverManager * @throws SQLException * if a database error occurs. */public Driver() throws SQLException {// Required for Class.forName().newInstance()}}The core code is the static code block (static {} indicates that the code is executed once when the class is loaded, and only once ), static code disconnection means that the Driver class is instantiated and registered to the JDBC java. SQL. driverManager class, so let's take a look at the JDBC DriverManager. registerDriver:
/** * Registers the given driver with the <code>DriverManager</code>. * A newly-loaded driver class should call * the method <code>registerDriver</code> to make itself * known to the <code>DriverManager</code>. * * @param driver the new JDBC Driver that is to be registered with the * <code>DriverManager</code> * @exception SQLException if a database access error occurs */ public static synchronized void registerDriver(java.sql.Driver driver)throws SQLException {if (!initialized) { initialize();} DriverInfo di = new DriverInfo();di.driver = driver;di.driverClass = driver.getClass();di.driverClassName = di.driverClass.getName();// Not Required -- drivers.addElement(di);writeDrivers.addElement(di); println("registerDriver: " + di);/* update the read copy of drivers vector */readDrivers = (java.util.Vector) writeDrivers.clone(); }You can add com. mysql. jdbc. Driver to the readDrivers member variable of DriverManager. This variable is needed for database connection later.
Check the code above and find that initialize () is also called. Check the initialize () source code to see that it calls loadInitialDrivers (). The main function of this function is to load the default JDBC driver, after registerDriver is executed, the console output statement is:
JdbcOdbcDriver class loadedregisterDriver: driver[className=sun.jdbc.odbc.JdbcOdbcDriver,sun.jdbc.odbc.JdbcOdbcDriver@134e4fb]DriverManager.initialize: jdbc.drivers = nullJDBC DriverManager initializedregisterDriver: driver[className=com.mysql.jdbc.Driver,com.mysql.jdbc.Driver@157c2bd]
We can see that JdbcOdbcDriver is loaded first, and then the MySQL driver we added is loaded.
After obtaining the link and loading the driver, how can I get the connection? Continue with the getConnection () of DriverManager ():
// Worker method called by the public getConnection() methods. private static Connection getConnection(String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {java.util.Vector drivers = null; /* * When callerCl is null, we should check the application's * (which is invoking this class indirectly) * classloader, so that the JDBC driver class outside rt.jar * can be loaded from here. */synchronized(DriverManager.class) { // synchronize loading of the correct classloader. if(callerCL == null) { callerCL = Thread.currentThread().getContextClassLoader(); } } if(url == null) { throw new SQLException("The url cannot be null", "08001");} println("DriverManager.getConnection(\"" + url + "\")"); if (!initialized) { initialize();}synchronized (DriverManager.class){ // use the readcopy of drivers drivers = readDrivers; }// Walk through the loaded drivers attempting to make a connection.// Remember the first exception that gets raised so we can reraise it.SQLException reason = null;for (int i = 0; i < drivers.size(); i++) { DriverInfo di = (DriverInfo)drivers.elementAt(i); // If the caller does not have permission to load the driver then // skip it. if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {println(" skipping: " + di);continue; } try {println(" trying " + di);Connection result = di.driver.connect(url, info);if (result != null) { // Success! println("getConnection returning " + di); return (result);} } catch (SQLException ex) {if (reason == null) { reason = ex;} }} // if we got here nobody could connect.if (reason != null) { println("getConnection failed: " + reason); throw reason;} println("getConnection: no suitable driver found for "+ url);throw new SQLException("No suitable driver found for "+ url, "08001"); }This function has a lot of code, but the core code we pay attention to is as follows:
Connection result = di.driver.connect(url, info);
Di is an object contained in readDrivers, which is called com. mysql. jdbc. but the above Code shows that it only contains one constructor and a static code segment. Where does the connect function come from?
Don't forget that com. mysql. jdbc. driver inherits from NonRegisteringDriver, which is also a class under the MySQL driver. Go to this class and find the connect function:
Package com. mysql. jdbc;/*** omitting references and comments ***/public class NonRegisteringDriver implements java. SQL. driver {/*** omitting other functions and comments ***/public java. SQL. connection connect (String url, Properties info) throws SQLException {Properties props = null; if (props = parseURL (url, info) = null) {return null ;} try {Connection newConn = new com. mysql. jdbc. connection (host (props), port (props), props, database (props), url, this); return newConn;} catch (SQLException sqlEx) {// Don't wrap SQLExceptions, throw // them un-changed.throw sqlEx;} catch (Exception ex) {throw new SQLException (Messages. getString ("NonRegisteringDriver.17") // $ NON-NLS-1 $ + ex. toString () + Messages. getString ("NonRegisteringDriver.18"), // $ NON-NLS-1 $ SQLError. SQL _STATE_UNABLE_TO_CONNECT_TO_DATASOURCE );}}}
NonRegisteringDriver is also the implementation of java. SQL. Driver, And the return is the implementation of Connection in JDBC. Therefore, we can obtain the Connection of MySQL from DriverManager through interface programming.
Summary
This is the end of the analysis of JDBC. If you are interested, you can take a look at the source code of other database drivers, because it is based on JDBC, so most of them are similar.
What is jdbc?
JDBC provides a standard API for tools/database developers to build more advanced tools and interfaces so that database developers can use pure Java APIs to write database applications, JDBC is also a trademark name. With JDBC, it is easy to send SQL statements to various relational data. In other words, with JDBC APIs, you do not have to write a program for accessing the Sybase Database, write another program for accessing the Oracle database, or write another program for accessing the Informix database, programmers only need to use the jdbc api to write a program. It can send SQL calls to the corresponding database. At the same time, the combination of Java and JDBC makes it unnecessary for programmers to write different applications for different platforms. They only need to write the program once to run it on any platform, this is also the advantage of the Java language "writing once, running everywhere. The Java database connection architecture is a standard method for connecting Java applications to databases. JDBC is an API for Java programmers and an interface model for service providers that connect to databases. As an API, JDBC provides standard interfaces for program development and provides standard methods for database vendors and third-party middleware vendors to connect to databases. JDBC uses existing SQL standards and supports connection standards with other databases, such as bridging between ODBC. JDBC implements all these standard-oriented interfaces with simple, strictly-defined types, and high-performance implementations. Java is a powerful, secure, easy to use, easy to understand, and can be automatically downloaded from the network. It is an outstanding language for writing database applications. All you need is the method of dialog between Java applications and different databases. JDBC serves as a mechanism for this purpose. JDBC extends Java functions. For example, you can use Java and JDBC APIs to publish a webpage containing an applet, and the information used by the applet may come from a remote database. Enterprises can also use JDBC to connect all employees to one or more internal databases over the Intranet (even if these employees use different operating systems such as Windows, Macintosh, and UNIX ). As more and more programmers begin to use the Java programming language, the requirements for convenient access to the database from Java are also increasing. MIS administrators like the combination of Java and JDBC because it makes information dissemination easy and economical. Enterprises can continue to use their installed databases and easily access information, even if the information is stored on different database management systems. The development period of new programs is very short. Installation and version control will be greatly simplified. A programmer can write an application only once or update it only once, and then put it on the server. then anyone can get the latest version of the application. For commercial sales information services, Java and JDBC can provide external customers with a better way to obtain information updates. JDBC can be used to establish a connection with a database, send SQL statements, and process the results. The following code snippet provides a basic example of the above three steps: Connection con = DriverManager. getConnection ("jdbc: odbc: wombat", "login", "password"); Statement stmt = con. createStatement (); ResultSet rs = stmt.exe cuteQuery ("SELECT a, B, c FROM Table1"); while (rs. next () {int x = rs. getInt ("a"); String s = rs. getString ("B"); float ...... remaining full text>
Jdbc connection to the database
No oracle driver ~~~
It may be that the driver is not packaged in your war package.