Driver Class Name and JDBC URL Format

Source: Internet
Author: User
Tags end execution failover connect sql mysql socket version

The name of the class that implements Java.sql.Driver in MySQL connector/j is ' com.mysql.jdbc.Driver '. The ' ' class name is also usable to remain backwards-compatible with MM. Mysql. You are should use this class name when registering the driver, or when otherwise configuring software to use MySQL connector/ J.

The JDBC URL format for MySQL connector/j are as follows, with items in square brackets ([,]) being optional:
Jdbc:mysql://[host][,failoverhost ...] [:p ort]/[database][?propertyname1][=propertyvalue1][&propertyname2][=propertyvalue2] ...
IF the hostname is isn't specified, it defaults to ' '. If the port is not specified, it defaults to ' 3306 ', the default port number for MySQL servers.

Starting with version 3.0.12 and 3.1.2, connector/j supports multiple hosts with ports, separated by commas:
jdbc:mysql://[host:port],[host:port].../[database][?propertyname1][=propertyvalue1][&propertyname2][= PropertyValue2] ...
If the database is not specified, the connection would be made with no ' current ' database. In this case, you'll need to either call the ' Setcatalog () ' method on the Connection instance, issue a ' use dbname ' Quer Y or Fully-specify table names using the database name (i.e. ' SELECT dbname.tablename.colname from Dbname.tablename ... ') I N your SQL. Not specifying the "database to" upon connection is generally only useful when building tools, work with multiple Da Tabases, such as GUI database managers.

MySQL connector/j has fail-over support. This is allows the driver to Fail-over to any number of "slave" hosts with still perform read-only. Fail-over only happens when the connection was in a autocommit (true) state, because Fail-over can do not happen when A transaction is in progress. Most good application servers and connection pools set autocommit to ' true ' on the end of every transaction/connection use . The Fail-over functionality has the following behavior:if the URL property "AutoReConnect" are false:failover only happen s at connection initialization, and failback occurs when the driver determines then the "the" has become-available AG Ain If The URL property "AutoReConnect" was true:failover happens when the driver determines this connection has D (before every query), and falls back to the the "host" when it determines this host has become available (again R Queriesbeforeretrymaster queries have been issued). In either case, whenever you are conNected to a "failed-over" server, the connection is set to read-only state, so queries that would modify data would ha ve exceptions thrown (the query would never be processed by the MySQL server).

You could specify additional properties to the JDBC driver, either by placing them in a java.util.Properties instance and PA Ssing that instance to the DriverManager when you connect, or by adding them to the "end of your JDBC URL as Name-value Pai Rs. The needs to is preceeded with a ' character ' and additional Name-value pair properties are by An ' & ' character. The properties, their definitions and their default values are covered in the following table:

Table 2.1. Connection Properties
Connection/authentication user the user to connect as no password the "password to" when connecting no socketfactory the Name of the class that's driver should use for creating sockets connections to the server. This class must implement the interface ' Com.mysql.jdbc.SocketFactory ' and have to public No-args constructor. No com.mysql.jdbc.StandardSocketFactory connecttimeout Timeout for sockets connect (in milliseconds) with 0 being no Timeo Ut. only works on JDK-1.4 or newer. Defaults to ' 0 '. No 0 sockettimeout Timeout on network socket operations (0, the default means no Timeout). No 0 useconfigs Load The comma-delimited list of configuration properties before parsing the URL or applying user-specifie D Properties. These configurations are explained are in the ' configurations ' of the documentation. No interactiveclient Set The client_interactive flag, which tells MySQL to timeout connections on based T instead of Wait_timeout No false Propertiestransform an implementation of Com.mysql.jdbc.ConnectionPropertiesTransform that the driver would use to modify URL properties passed to the driver be Fore attempting a connection No usecompression use zlib compression while communicating with the server (true/false)? Defaults to ' false '. No false high availability and clustering AutoReConnect Should the driver try to re-establish bad connections? No false autoreconnectforpools use a reconnection strategy appropriate for connection pools (defaults to ' false ') no false Failoverreadonly when failing over in AutoReConnect mode, should the connection is set to ' read-only '? No true maxreconnects Maximum number of reconnects to attempt if AutoReConnect was true, default is ' 3 '. No 3 initialtimeout If autoreconnect is enabled, the initial time to wait between re-connect attempts (in seconds, default S to ' 2 '). No 2 queriesbeforeretrymaster number of queries to issue before falling back to master when failed over (when using multi- Host failover). Whichever condition is met FIrst, ' queriesbeforeretrymaster ' or ' secondsbeforeretrymaster ' to cause a attempt to is made to reconnect to the master . Defaults to 50. No Secondsbeforeretrymaster How long should the driver and when failed over, before attempting to reconnect to the MA Ster server? Whichever condition is met-A, ' queriesbeforeretrymaster ' or ' secondsbeforeretrymaster ' 'll cause a attempt to be mad E to reconnect to the master. Seconds, defaults to No. allowmultiqueries Allow the use of ' by ' to delimit multiple queries NE statement (true/false, defaults to ' false "No false UseSSL use SSL when communicating with the server (True/false), Def Aults to ' false ' No false requireSSL Require SSL connection if usessl=true? (Defaults to ' false '). No false Allowurlinlocalinfile Should The driver allow URLs in ' LOAD DATA local INFILE ' statements? No false paranoid Take measures to prevent exposure sensitive information in error messages and clear data structures hold ing SensItive data when possible? (Defaults to ' false ') No false Performance Extensions metadatacachesize the number of queries to Cacheresultsetmetadata for if Cacheresultsetmet Adata is set to ' true ' (default) No prepstmtcachesize IF prepared statement caching are enabled, how many prepared St Atements should be cached? No Prepstmtcachesqllimit IF Prepared statement caching is enabled, what ' the largest SQL the driver would cache the par Sing for? No 256 cachecallablestmts Should the driver cache the parsing stage of callablestatements No false Cacheprepstmts Should t He driver cache the parsing stage of preparedstatements? No false Cacheresultsetmetadata Should the driver cache ResultSetMetaData for statements and preparedstatements? (Req. jdk-1.4+, True/false, default ' false ') No false Cacheserverconfiguration Should The driver cache the results of ' show VARIABLES ' and ' show Collation ' on a Per-ur L basis? No false Dontunpackbinaryresults Should The driver delay unpacking results from SErver-side prepared statements until the values are for? No false Dynamiccalendars Should The driver retrieve the default calendar when required, or cache it per Connection/sessio N? No false elidesetautocommits If using MySQL-4.1 or newer, should the driver only issue ' set Autocommit=n ' queries when the Server ' s state doesn ' t match the requested State by Connection.setautocommit (Boolean)? No false usefastintparsing Use internal string->integer conversion routines to avoid excessive object creation? No true Usenewio Should The driver use the JAVA.NIO.* Interfaces for network communication (TRUE/FALSE), defaults to ' Fals E ' No false usereadaheadinput use newer, optimized non-blocking, buffered input stream when reading from the server? No true Debuging/profiling Logger The name of a class that implements ' Com.mysql.jdbc.log.Log ' and would be used to log me Ssages to. (Default is ' Com.mysql.jdbc.log.StandardLogger ', which logs to STDERR) No Com.mysql.jdbc.log.StandardLogger ProfileSQL Trace queries and their execution/fetch times to the configured logger (true/false) defaults to ' false ' No false profil ESQL deprecated, use ' profilesql ' instead. Trace queries and their execution/fetch times in STDERR (true/false) defaults to ' false ' No Maxquerysizetolog Controls the Maximum length/size of a query that'll get logged when profiling or tracing No 2048 packetdebugbuffersize the maximum n Umber of packets to retain the ' Enablepacketdebug ' is true No slowquerythresholdmillis If ' logslowqueries ' is enabled, How long should a query (in MS) before it is logged as ' slow '? No Useusageadvisor Should The driver issue ' usage ' warnings advising-proper and efficient usage of JDBC and MySQL Con Nector/j to the log (True/false, defaults to ' false ')? No false Dumpqueriesonexception Should The driver dump the contents of the query sent to the "server in" for SQL Exceptions? No false Enablepacketdebug when enabled, a ring-buffer of ' packetdebugbuffersize ' packets would Be kept, and dumped then exceptions are thrown in key areas in the driver ' s code No false explainslowqueries If ' Logslowq Ueries ' is enabled, should the driver automatically issue a ' EXPLAIN ' on the server and send the results to the Configure D log at a WARN level? No false Logslowqueries Should queries that take longer than ' slowquerythresholdmillis ' to be logged? No false Traceprotocol Should trace-level network protocol be logged? No false Miscellaneous Useunicode Should The driver use Unicode character encodings when handling? Should is used when the driver can ' t determine the character set mapping, or your are trying to ' force ' driver to Use a character set this MySQL either doesn ' t natively support (such as UTF-8), True/false, defaults to ' true ' No false ch Aracterencoding If ' Useunicode ' is set to true, what character encoding should the driver use when dealing with strings? (Defaults is to ' AutoDetect ') No Charactersetresults Character set to tell the server to RETUrn results as. No connectioncollation If set, tells the server to use this collation via ' Set Connection_collation ' no Allownanandinf Sho Uld the driver allow NaN or//+ INF values in preparedstatement.setdouble ()? No false Autodeserialize Should The driver automatically detect and De-serialize objects in BLOB stored? No false Capitalizetypenames capitalize type names in DatabaseMetaData? (usually only useful if using WebObjects, True/false, defaults to ' false ') No false Clobberstreamingresults This'll cause a ' streaming ' ResultSet to is automatically closed, and any oustanding da Ta still streaming from the the "discarded if another query is executed before all" the data has been read from the Server. No false Continuebatchonerror Should The driver continue processing batch if one commands statement. The JDBC spec allows either way (defaults to ' true '). No true emulatelocators N/a No false ignorenontxtables Ignore non-transactional table warning for rollback? (dEfaults to ' false '). No false Jdbccomplianttruncation Should The driver throw java.sql.DataTruncation exceptions when data was truncated as is R Equired by the JDBC specification when connected to a server that supports warnings (MySQL 4.1.0 and newer)? No true maxRows the maximum number of rows to return (0, the default means return all rows). No-1 pedantic Follow The JDBC spec to the letter. No false Relaxautocommit If The version of MySQL the driver connects to does not support transactions, still allow calls T o commit (), rollback () and Setautocommit () (True/false, defaults to ' false ')? No false Rollbackonpooledclose Should The driver issue a rollback () when the logical connection into a pool is closed? No true Servertimezone Override detection/mapping of TimeZone. Used when timezone from server doesn ' t map to Java timezone No strictfloatingpoint Used/In older versions of Complian Ce test No false strictupdates Should The driver do strict checking (all primary keys selected) of UPDATable result Sets (True, false, defaults to ' true ')? No true Tinyint1isbit Should The driver treat the datatype TINYINT (1) as the BIT type (because the server silently convert S BIT-> TINYINT (1) when creating tables)? No true Ultradevhack Create preparedstatements for Preparecall () when required, because Ultradev is broken and issues a PR Eparecall () for _all_ statements? (True/false, defaults to ' false ') No false usehostsinprivileges Add ' @hostname ' to the users in Databasemetadata.getcolumn/tableprivileges () (True/false), Defaults to ' true '. No true useoldutf8behavior use the UTF-8 behavior the driver did when communicating with 4.0 and older servers No false US Eonlyservererrormessages Don ' t prepend ' standard ' SQLState error messages to error messages by the server. No true USESERVERPREPSTMTS Use server-side prepared statements if the server supports them? (Defaults to ' true '). No true usesqlstatecodes use SQL Standard state codes instead of ' legacy ' X/open/sql the state codes (trUe/false), default is ' true ' No true usestreamlengthsinprepstmts Honor stream length parameter in Preparedstatement/result Set.setxxxstream () method calls (True/false, defaults to ' true ')? No true Usetimezone Convert time/date types between client and server TimeZones (True/false, defaults to ' false ')? No false useunbufferedinput Don ' t use Bufferedinputstream for reading data from the server no true Zerodatetimebehavior Wh At should happen then driver encounters DATETIME values that are composed entirely of zeroes (used by MySQL to Represe NT Invalid dates)? Valid values are ' exception ', ' Round ' and ' converttonull '. No exception
Connector/j also supports access to MySQL via Named Pipes on Windows nt/2000/xp using the ' namedpipesocketfactory ' as a pl Ugin-socket factory via the ' Socketfactory ' property. If you don ' t use a ' Namedpipepath ' property, the default of ' \\.\pipe\mysql ' would be used. If you use the namedpipesocketfactory, the hostname and port number values in the JDBC URL would be ignored.

Adding the following property to your URL would enable the namedpipesocketfactory:


Named pipes only work when connecting to a MySQL server on the same physical machine as the one of the JDBC driver is being u Sed on. In simple performance tests, it appears this named pipe access is between 30%-50% faster the than the standard TCP/IP access.

Can create your own socket factories by following the example code in Com.mysql.jdbc.NamedPipeSocketFactory, or COM.M Ysql.jdbc.StandardSocketFactory.
Posted 2005-01-04 12:54:00.0

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: 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.