MySQL driver read------Connection connection, based on JDBC-----5.1.26

Source: Internet
Author: User
Tags throwable

Programs that generally get database connections

Class.forName ("Com.mysql.jdbc.Driver"), final Connection Connection = (Connection) drivermanager.getconnection ("jdbc : Mysql://localhost:3306/testdb "," guoxiaoming "," guoxiaoming ");

-----------------------------

Register MySQL driver class next time, we are now focusing on the establishment of connection

-----------------------------

Public interface Connection  extends Wrapper {

The JDK's connection provides a standard, connection (session) to a particular database. Executes the SQL statement in the connection context and returns the result.

The connection interface is implemented by the database-driven class, which holds the IO class in the database connection.

The DriverManager class in JDBC encapsulates a unified approach to acquiring connection objects

public static Connection getconnection (string url, string user, String password) throws SQLException {        Java.util.Prop Erties info = new Java.util.Properties ();        Gets the ClassLoader of the code that called this method, May//IS NULL. ClassLoader CALLERCL = Drivermanager.getcallerclassloader (), if (user! = null) {    info.put ("user", user);} if (password! = null) {    info.put ("password", password);}        Return (getconnection (URL, info, CALLERCL));}

Enter the getconnection (URL,INFO,CALLERCL) method to see what you can see,

Connection result = Di.driver.connect (URL, info);

The code eventually gets the connection object

The corresponding driver driver class is implemented in JDBC

public class Nonregisteringreplicationdriver extends Nonregisteringdriver {public nonregisteringreplicationdriver () Throws SQLException {super ();} /* * (NON-JAVADOC) * *  @see java.sql.driver#connect (java.lang.String, java.util.Properties) */public Connection Connect (String URL, Properties info) throws SQLException {return connectreplicationconnection (URL, info);}}

See the Connectreplicationconnection (Url,info) method in the parent class Nonregisteringdriver class

return new Replicationconnection (Masterprops, slavesprops);

See the class

Public replicationconnection (Properties masterproperties,properties slaveproperties) throws SQLException { This.driver = new Nonregisteringdriver (); this.slaveproperties = Slaveproperties;this.masterproperties = masterproperties;        This.initializemasterconnection ();        This.initializeslaveconnection ();        This.currentconnection = this.masterconnection;}

Initialized two links, one is masterconnection and the other is slaveconnection

See notes

/** * Connection that opens the connections, one, one, replication Master, and * another to one or more slaves, and decide s to use master when the connection * are not read-only, and use slave (s) if the connection is read-only. *  * @version $Id: replicationconnection.java,v 1.1.2.1 2005/05/13 18:58:38 *          mmatthews EXP $ */

We finally saw in the Connectionimpl class

protected static Connection getinstance (String hosttoconnectto,int porttoconnectto, Properties info, string Databasetoconnectto,string URL) throws SQLException {if (! UTIL.ISJDBC4 ()) {return new Connectionimpl (Hosttoconnectto, Porttoconnectto, Info,databasetoconnectto, URL);} Return (Connection) util.handlenewinstance (jdbc_4_connection_ctor,new object[] {hosttoconnectto, integer.valueof ( Porttoconnectto), Info,databasetoconnectto, url}, null);}

Instantiate a subclass of the class

By constructing a method

Public Jdbc4connection (string hosttoconnectto, int porttoconnectto, Properties info, string Databasetoconnectto, String URL) throws SQLException {super (Hosttoconnectto, Porttoconnectto, info, databasetoconnectto, URL);//TODO auto-generated constructor stub}

In its parent class

Protected Connectionimpl (String hosttoconnectto, int porttoconnectto, Properties info,string Databasetoconnectto, String URL) throws SQLException {This.connectioncreationtimemillis = System.currenttimemillis (); if ( Databasetoconnectto = = null) {Databasetoconnectto = "";}

Emphasis on methods

public void Createnewio (Boolean isforreconnect) throws SQLException {synchronized (Getconnectionmutex ()) {// Synchronization not needed for *new* connections, but defintely for//connections going through fail-over, since we might Get the//New connection up and running *enough* to start sending//cached or Still-open server-side prepared statements O ver//to the backend before we get a chance to re-prepare them ... Properties mergedprops  = exposeasproperties (This.props), if (!gethighavailability ()) {connectonetryonly ( Isforreconnect, mergedprops); return;} Connectwithretries (Isforreconnect, Mergedprops);}}

In the end we see concrete links implemented in the Coreconnect method.

private void Coreconnect (Properties mergedprops) throws sqlexception,ioexception {int newPort = 3306; String newhost = "localhost"; String protocol = mergedprops.getproperty (Nonregisteringdriver.protocol_property_key), if (protocol! = NULL) {//"new" Style Urlif ("TCP". Equalsignorecase (protocol)) {newhost = Normalizehost (Mergedprops.getproperty ( Nonregisteringdriver.host_property_key)); newPort = Parseportnumber (Mergedprops.getproperty ( Nonregisteringdriver.port_property_key, "3306"));} else if ("pipe". Equalsignorecase (protocol)) {Setsocketfactoryclassname (NamedPipeSocketFactory.class.getName ()); String path = Mergedprops.getproperty (Nonregisteringdriver.path_property_key), if (path! = null) { Mergedprops.setproperty (namedpipesocketfactory.named_pipe_prop_name, Path);}} else {//normalize for all unknown Protocolsnewhost = Normalizehost (Mergedprops.getproperty (nonregisteringdriver.host_ Property_key)); newPort = Parseportnumber (Mergedprops.getproperty (Nonregisteringdriver.port_property_key, "3306"));}} else {string[] Parsedhostportpair = Nonregisteringdriver.parsehostportpair (this.hostportpair); newHost = Parsedhostportpair[nonregisteringdriver.host_name_index];newhost = Normalizehost (newHost); if (parsedHostPortPair[ NONREGISTERINGDRIVER.PORT_NUMBER_INDEX]! = null) {NewPort = Parseportnumber (parsedhostportpair[ Nonregisteringdriver.port_number_index]);}} This.port = Newport;this.host = Newhost;this.io = new Mysqlio (Newhost, Newport,mergedprops, Getsocketfactoryclassname () , GetProxy (), Getsockettimeout (), this.largeRowSizeThreshold.getValueAsInt ()); This.io.doHandshake (This.user, This.password,this.database);}

Implemented in the construction method of the new Mysqlio class

 Public Mysqlio (string host, int port, Properties props, String socketfactoryclassname, Mysqlconnection conn,                int sockettimeout, int usebufferrowsizethreshold) throws IOException, SQLException {this.connection = conn; if (This.connection.getEnablePacketDebug ()) {This.packetdebugringbuffer = new linkedlist<string        Buffer> ();                } This.traceprotocol = This.connection.getTraceProtocol ();                This.useautoslowlog = This.connection.getAutoSlowLog ();        This.usebufferrowsizethreshold = Usebufferrowsizethreshold;        This.usedirectrowunpack = This.connection.getUseDirectRowUnpack ();        This.logslowqueries = This.connection.getLogSlowQueries ();        This.reusablepacket = new Buffer (initial_packet_size);        This.sendpacket = new Buffer (initial_packet_size);        This.port = port;        This.host = host;        This.socketfactoryclassname = Socketfactoryclassname; This.socketfactory = CREAtesocketfactory ();                This.exceptioninterceptor = This.connection.getExceptionInterceptor ();                try {this.mysqlconnection = This.socketFactory.connect (This.host, this.port, props);        if (sockettimeout! = 0) {try {this.mysqlConnection.setSoTimeout (sockettimeout); } catch (Exception ex) {/* Ignore if the platform does not support it */}} This.mysqlconnec        tion = This.socketFactory.beforeHandshake (); if (This.connection.getUseReadAheadInput ()) {this.mysqlinput = new Readaheadinputstream (this.mysqlConnection.getIn        Putstream (), 16384, This.connection.getTraceProtocol (), This.connection.getLog ());        } else if (This.connection.useUnbufferedInput ()) {this.mysqlinput = This.mysqlConnection.getInputStream ();        } else {this.mysqlinput = new Bufferedinputstream (This.mysqlConnection.getInputStream (), 16384); } This.mysqloutput =New Bufferedoutputstream (This.mysqlConnection.getOutputStream (), 16384);        This.isinteractiveclient = This.connection.getInteractiveClient ();        This.profilesql = THIS.CONNECTION.GETPROFILESQL ();        This.autogeneratetestcasescript = This.connection.getAutoGenerateTestcaseScript ();        This.needtograbqueryfrompacket = (This.profilesql | |        this.logslowqueries | |        This.autogeneratetestcasescript); if (This.connection.getUseNanosForElapsedTime () && util.nanotimeavailable ()) {this.usenanosforelapsedtime = True;this.querytimingunits = messages.getstring ("nanoseconds");} else {this.querytimingunits = messages.getstring ("Milliseconds");}        if (This.connection.getLogSlowQueries ()) {calculateslowquerythreshold ();} } catch (IOException Ioex) {throw sqlerror.createcommunicationsexception (this.connection, 0, 0, Ioex, getexception        Interceptor ()); }    }

This.mysqlconnection = This.socketFactory.connect (this.host,this.port, props);
This returns the socket object

Among the Standardsocketfactory classes
if (this.host! = null) {if (!) ( Wantslocalbind | | Wantstimeout | | Needsconfigurationbeforeconnect)) {inetaddress[] possibleaddresses = Inetaddress.getallbyname (this.host); Throwable caughtwhileconnecting = null;//need to loop through all possible addresses, in case//someone have IPV6 Configur Ed (SuSE, for example ...) for (int i = 0; i < possibleaddresses.length; i++) {try {this.rawsocket = new Socket (possibleaddresses[i],port); Configu Resocket (this.rawsocket, props); catch (Exception ex) {caughtwhileconnecting = ex;}} if (Rawsocket = = null) {Unwrapexceptiontoproperclassandthrowit (caughtwhileconnecting);}} else {//must explicitly state-due to ClassLoader issues//when running on older JVMs:(try {inetaddress[] Possiblead Dresses = Inetaddress.getallbyname (this.host); Throwable caughtwhileconnecting = Null;object localsockaddr = null; Class<?> inetsocketaddressclass = null; Constructor<?> Addrconstructor = null;try {inetsocketaddressclass = Class.forName ("Java.net.InetSocketAddress ") Addrconstructor = Inetsocketaddressclass.getconstructor (new class[] {inetaddress.class, Integer.type}), if (wantslocalbind) {localsockaddr = Addrconstructor.newinstance (new object[] {inetaddress.getbyname ( Localsockethostname), new Integer (0/* * Use ephemeral * port */)});}} catch (Throwable ex) {Unwrapexceptiontoproperclassandthrowit (ex);} Need to loop through all possible addresses, in case//someone have IPV6 configured (SuSE, for example ...) for (int i = 0; i < possibleaddresses.length; i++) {try {this.rawsocket = new Socket (); Configuresocket (This.rawsocket, props); Object sockaddr = Addrconstructor.newinstance (new object[] {possibleaddresses[i],integer.valueof (port)});// Bind to the local port if not using the ephemeral portif (localsockaddr! = null) {Socketbindmethod.invoke (rawsocket,new Ob Ject[] {localsockaddr});} Connectwithtimeoutmethod.invoke (rawsocket,new object[] {sockaddr,integer.valueof (connectTimeout)}); catch (Exception ex) {this.rawsocket = Null;caughtwhileconnecting = ex;}} if (This.rawsocket = = null) {Unwrapexceptiontoproperclassandthrowit (caughtwhileconnecting);}} catch (Throwable t) {Unwrapexceptiontoproperclassandthrowit (t);}} return this.rawsocket;}

The possibility of multiple IPs for host may be connected to one of the IPs, then break exits

MySQL driver read------Connection connection, based on JDBC-----5.1.26

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.