Java MySQL JDBC Driver class and URL example |

Опубликовано 25.07.2017 | Автор:

The name of the class that implements java. Driver class name is also usable for backward compatibility with MM. The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets [ ] being optional:. If no hosts are not specified, the host name defaults to localhost. If the port for a host is not specified, it defaults to , the default port number for MySQL servers. If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog method on the Connection instance, or fully specify table names using the database name that is, SELECT dbname.

Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers. The following is an alternate format for JDBC URLs connecting to a MySQL server, which is mandatory for IPv6 connections, but can also be used with IPv4 items in square brackets [ ] are optional:.

Use the key-value pair to specify a custom named pipe. Notice that the alternate format greatly simplifies the URL for a named pipe connection on Windows. Keys other than protocol , path , host , and port are treated as host-specific configuration properties, which allow per-host overrides of configuration properties set for multi-host connections that is, when using failover, load balancing, or replication.

Limit the overrides to user, password, network timeouts, and statement and metadata cache sizes; the effects of other per-host overrides are not defined. The ways to set other configuration properties for the connection are the same for the general and the alternate URL formats; see Setting Configuration Properties. Unless otherwise noted, properties can be set for a DataSource object or for a Connection object.

MySQL Database Tutorial

DataSource which is the preferred method when using implementations of java. Properties instance passed to DriverManager. As a JDBC URL parameter in the URL given to java. The name of the class that the driver should use for creating socket connections to the server. Timeout for socket connect in milliseconds , with 0 being no timeout. Timeout on network socket operations 0, the default means no timeout. A comma-delimited list of classes that implement "com. ConnectionLifecycleInterceptor" that should notified of connection lifecycle events creation, destruction, commit, rollback, setCatalog and setAutoCommit and potentially alter the execution of these commands.

ConnectionLifecycleInterceptors are "stackable", more than one interceptor may be specified via the configuration property as a comma-delimited list, with the interceptors executed in order from left to right. Load the comma-delimited list of configuration properties before parsing the URL or applying user-specified properties. Comma-delimited list of classes that implement com. AuthenticationPlugin and which will be used for authentication unless disabled by "disabledAuthenticationPlugins" property.

Name of a class implementing com. AuthenticationPlugin which will be used as the default authentication plugin see below. It is an error to use a class which is not listed in "authenticationPlugins" nor it is one of the built-in plugins. It is an error to set as default a plugin which was disabled with "disabledAuthenticationPlugins" property. It is an error to set this value to null or the empty string i.

Comma-delimited list of classes implementing com. AuthenticationPlugin or mechanisms, i. The authentication plugins or mechanisms listed will not be used for authentication which will fail if it requires one of them. It is an error to disable the default authentication plugin either the one named by "defaultAuthenticationPlugin" property or the hard-coded one if "defaultAuthenticationPlugin" property is not set.

ConnectionPropertiesTransform that the driver will use to modify URL properties passed to the driver before attempting a connection. Maximum allowed packet size to send to server. Also, due to an internal dependency with the property "blobSendChunkSize", this setting has a minimum value of "" if "useServerPrepStmts" is set to "true". If enabled the driver will throw an exception for a queries issued on a stale or dead connection, which belong to the current transaction, but will attempt reconnect before the next query issued on the connection in a new transaction.

If autoReconnect is set to true, should the driver attempt reconnections at the end of every transaction? When using loadbalancing or failover, the number of times the driver should cycle through available hosts, attempting to connect. Between cycles, the driver will pause for ms if no servers are available.

When autoReconnect is enabled, and failoverReadonly is false, should we pick hosts to connect to on a round-robin basis? Number of queries to issue before falling back to the primary host when failed over when using multi-host failover. Setting both properties to 0 disables the automatic fall back to the primary host at transaction boundaries. How long should the driver wait, when failed over, before attempting to reconnect to the primary host? Time in seconds, defaults to By default, a replication-aware connection will fail to connect when configured master hosts are all unavailable at initial connection.

By default, a replication-aware connection will fail to connect when configured slave hosts are all unavailable at initial connection. If, when setting the connection to read-only state, none of the slave hosts are available, an SQLExeception is thrown back. If set to a non-zero value, the driver will report close the connection and report failure when Connection. Logical group of replication connections within a classloader, used to manage different groups independently. If not specified, live management of replication connections is disabled.

A globally unique name that identifies the resource that this datasource or connection is connected to, used for XAResource. URL to the client certificate KeyStore if not specified, use defaults. KeyStore type for client certificates NULL or empty means use the default, which is "JKS". Standard keystore types supported by the JVM are "JKS" and "PKCS12", your environment may have more available depending on what security products are installed and available to the JVM.

URL to the trusted root certificate KeyStore if not specified, use defaults. KeyStore type for trusted root certificates NULL or empty means use the default, which is "JKS". If "useSSL" is set to "true", overrides the cipher suites enabled for use on the underlying SSL sockets.

This may be required when using external JSSE providers or to specify cipher suites compatible with both MySQL server and used JVM. Allows special handshake roundtrip to get server RSA public key directly from server. Take measures to prevent exposure sensitive information in error messages and clear data structures holding sensitive data when possible?

What character encoding is used for passwords? Leaving this set to the default value null , uses the value set in "characterEncoding" if there is one, otherwise uses UTF-8 as default encoding. If the password contains non-ASCII characters, the password encoding must match what server encoding was set to when the password was created. If not specified, the public key will be retrieved from the server. Should the driver refer to the internal values of autocommit and transaction isolation that are set by Connection. Should the driver use the in-transaction state provided by the MySQL protocol to determine if a commit or rollback should actually be sent to the database?

If prepared statement caching is enabled, how many prepared statements should be cached? CacheAdapterFactory, which will be used to create caches for the parsed representation of client-side prepared statements. Should the driver always communicate with the database when Connection. If set to false, the driver will only communicate with the database when the requested transaction isolation is different than the whichever is newer, the last value that was set via Connection. Should the driver maintain various internal timers to enable idle time calculations as well as more verbose error messages when the connection to the server fails?

Connect to MySQL with JDBC driver

Setting this property to false removes at least two calls to System. Note that this value cannot exceed the value of "maxAllowedPacket" and, if that is the case, then this value will be corrected automatically. Should the driver cache the parsing stage of CallableStatements. Should the driver cache the parsing stage of PreparedStatements of client-side prepared statements, the "check" for suitability of server-side prepared and server-side prepared statements themselves?

Should the driver cache ResultSetMetaData for Statements and PreparedStatements? The driver will call setFetchSize n with this value on all newly-created Statements. Stops checking if every INSERT statement contains the "ON DUPLICATE KEY UPDATE" clause. Also be aware that, in this case, the list of generated keys returned may not be accurate. Setting this property to true relaxes this constraint, and can be more memory efficient for some applications.

Also the automatic closing of the Statement and current ResultSet in Statement. Sets the default escape processing behavior for Statement objects.

Mysql driver class

When enabled, query timeouts set via Statement. High-load environments might want to consider disabling this functionality. Should the driver close result sets on Statement. What size result set row should the JDBC driver consider "large", and thus use a more memory-efficient way of representing the row internally? This tends to work better than round-robin, as the randomness will somewhat account for spreading loads where requests vary in response time, while round-robin can sometimes lead to overloaded nodes if there are variations in response times across the workload. If none of the servers listed in the affinity list is responsive, the driver then refers to the "random" strategy to proceed with choosing the next server.

Should the driver issue appropriate statements to implicitly set the transaction access mode on server side when Connection. Should the driver use multiqueries irregardless of the setting of "allowMultiQueries" as well as rewriting of prepared statements for INSERT into multi-value inserts when executeBatch is called? Notice that this has the potential for SQL injection if using plain java. Only the sub-set of the hosts enumerated in the main hosts section in this URL will be used and they must be identical in case and type, i.

Use newer result set row unpacking code that skips a copy from network buffers to a MySQL packet instance and instead reads directly into the result set row data buffers. Always use the character encoding routines built into the JVM, rather than using lookup tables for single-byte character sets? Use newer, optimized non-blocking, buffered input stream when reading from the server? The name of a class that implements "com. Log" that will be used to log messages to. StandardLogger", which logs to STDERR.

Should the driver dump the SQL it is executing, including server-side prepared statements to STDERR? The name of a class that implements the com. JDBC4ClientInfoProvider interface in order to support JDBC Should the driver dump the field-level metadata of a result set into the exception message when ResultSet. Should the driver dump the contents of the query sent to the server in the message for SQLExceptions? Include the output of "SHOW ENGINE INNODB STATUS" in exception messages when deadlock exceptions are detected?

Include a current Java thread dump in exception messages when deadlock exceptions are detected? Should the driver log XA commands sent by MysqlXaConnection to the server, at the DEBUG level of logging? Name of a class that implements the interface com. If the usage advisor is enabled, how many rows should a result set contain before the driver warns that it is suspiciously large? Should the driver use Unicode character encodings when handling strings?

A comma-delimited list of user-defined key: Earlier versions of MySQL Server do not support connection attributes, causing this configuration option to be ignored. When "useBlobToStoreUTF8OutsideBMP" is set to "true", column names matching the given regex will still be treated as BLOBs unless they match the regex specified for "utf8OutsideBmpIncludedColumnNamePattern".

The regex must follow the patterns used for the java. Used to specify exclusion rules to "utf8OutsideBmpExcludedColumnNamePattern". Sets the grace period to wait for a host being removed from a load-balanced connection, to be released when it is currently the active host.

Setting this property to "true" will give behavior that is congruent to JDBC This property is preferred over "useOldAliasMetadataBehavior" unless you need the specific behavior that it provides with respect to ResultSetMetadata. Should the driver automatically call. Should the driver automatically detect and de-serialize objects stored in BLOB fields?

Should the driver always treat BLOBs as Strings - specifically to work around dubious metadata returned by the server for GROUP BY clauses? Capitalize type names in DatabaseMetaData? The character encoding to use for sending and retrieving TEXT, MEDIUMTEXT and LONGTEXT values instead of the configured connection characterEncoding. Should the driver continue processing batch commands if one statement fails. Assumes the configured user has permissions to create databases. This could slow down connection initialization significantly. With this feature enabled, the driver will delay loading the actual Blob data until the one of the retrieval methods getInputStream , getBytes , and so forth on the blob data stream has been accessed.

For this to work, you must use a column alias with the value of the column to the actual name of the Blob. The feature also has the following restrictions: The SELECT that created the result set must reference only one table, the table must have a primary key; the SELECT must alias the original blob column name, specified as a string, to an alternate name; the SELECT must cover all columns that make up the primary key. Should the driver detect prepared statements that are not supported by the server, and replace them with client-side emulated versions?

These classes will be instantiated one per Connection instance, and all SQLExceptions thrown by the driver will be allowed to be intercepted by these interceptors, in a chained fashion, with the first class listed as the head of the chain. Should the driver always treat data from functions returning BLOBs as Strings - specifically to work around dubious metadata returned by the server for GROUP BY clauses? Pre-JDBC4 DatabaseMetaData API has only the getProcedures and getProcedureColumns methods, so they return metadata info for both stored procedures and functions.

JDBC4 was extended with the getFunctions and getFunctionColumns methods and the expected behaviours of previous methods are not well defined. Ignore non-transactional table warning for rollback? DataTruncation exceptions when data is truncated as is required by the JDBC specification when connected to a server that supports warnings MySQL 4.

When load-balancing is enabled for auto-commit statements via loadBalanceAutoCommitStatementThreshold , the statement counter will only increment when the SQL matches the regular expression. By default, every statement issued matches. When auto-commit is enabled, the number of statements which should be executed before triggering load-balancing to rebalance. Default value of 0 causes load-balanced connections to only rebalance when exceptions are encountered, or auto-commit is disabled and transactions are explicitly committed or rolled back.

Time in milliseconds between checks of servers which are unavailable, by controlling how long a server lives in the global blacklist. Logical group of load-balanced connections within a classloader, used to manage different groups independently. If not specified, live management of load-balanced connections is disabled. Fully-qualified class name of custom exception checker. LoadBalanceExceptionChecker interface, and is used to inspect SQLExceptions and determine whether they should trigger fail-over to another host in a load-balanced deployment.

Time in milliseconds to wait for ping response from each of load-balanced physical connections when using load-balanced Connection. The comparison is done using Class. Comma-delimited list of SQLState codes used by default load-balanced exception checker to determine whether a given SQLException should trigger failover. The SQLState of a given SQLException is evaluated to determine whether it begins with any value in the comma-delimited list.

The maximum number of rows to return 0, the default means return all rows. Should the driver return "true" for DatabaseMetaData. If a result set column has the CHAR type and the value does not fill the amount of characters specified in the DDL for the column, should the driver pad the remaining characters with space for ANSI compliance? When using XAConnections, should the driver ensure that operations on a given XID are always routed to the same physical connection?

This allows the XAConnection to support "XA START JOIN" after "XA END" has been called. This functionality requires a call to the database for metadata each time a result set of this type is created. Should the driver process escape codes in queries that are prepared? If the timeout given in Statement. Should the driver retain the Statement reference in a ResultSet after ResultSet.

Mysql driver class

This is not JDBC-compliant after JDBC Should the driver issue a rollback when the logical connection in a pool is closed? Send fractional part from TIMESTAMP seconds. If set to false, the nanoseconds value of TIMESTAMP values will be truncated before sending any data to the server. This option applies only to prepared statements, callable statements or updatable result sets.

StatementInterceptor" that should be placed "in between" query execution to influence the results. StatementInterceptors are "chainable", the results returned by the "current" interceptor will be passed on to the next in in the chain, from left-to-right order, as specified in this property. If the driver converts TINYINT 1 to a different type, should it use BOOLEAN instead of BIT for future compatibility with MySQL Date as a TIMESTAMP for the purposes of PreparedStatement. ON DUPLICATE KEY UPDATE" statements to be returned by the server.

Should the driver use the legacy behavior for "AS" clauses on columns and tables, and only return aliases if any for ResultSetMetaData. Use the UTF-8 behavior the driver did when communicating with 4. If migrating from an environment that was using server-side prepared statements, and the configuration property "useJDBCCompliantTimeZoneShift" set to "true", use compatible behavior when not using server-side prepared statements when sending TIMESTAMP values to the MySQL server. Use server-side prepared statements if the server supports them? Should the JDBC driver treat the MySQL type "YEAR" as a java.

What should happen when the driver encounters DATETIME values that are composed entirely of zeros used by MySQL to represent invalid dates? Valid values are "exception", "round" and "convertToNull". If you use the NamedPipeSocketFactory , the host name and port number values in the JDBC URL are ignored. To enable this feature, set the socketFactory property:. Named pipes only work when connecting to a MySQL server on the same physical machine where the JDBC driver is running.

To create your own socket factories, follow the example code in com. NamedPipeSocketFactory , or com. Installing the Driver and Configuring the CLASSPATH. Upgrading from an Older Version. JDBC-Specific Issues When Upgrading to MySQL Server 4. Properties Files for the useConfigs Option. Using Character Sets and Unicode. Connecting Using PAM Authentication. Mapping MySQL Error Numbers to JDBC SQLState Codes. Connecting to MySQL Using the JDBC DriverManager Interface. Using JDBC Statement Objects to Execute SQL. Using JDBC CallableStatements to Execute Stored Procedures. Advanced Load-balancing and Failover Configuration.

Properties and Descriptions user The user to connect as Since version: ConnectionPropertiesTransform that the driver will use to modify URL properties passed to the driver before attempting a connection Since version: Properties and Descriptions socksProxyHost Name or IP address of SOCKS host to connect through.

Time in seconds, defaults to 30 Default: Properties and Descriptions logger The name of a class that implements "com. StandardLogger", which logs to STDERR Default: Properties and Descriptions useUnicode Should the driver use Unicode character encodings when handling strings? JOIN" after "XA END" has been called Default: Posted by Joseph Saylor on March 5, Sign Up Login You must be logged in to post a comment.

Services Training Certification Consulting Support. Downloads MySQL Community Server MySQL NDB Cluster MySQL Shell MySQL Router MySQL Workbench. Documentation MySQL Reference Manual MySQL Workbench MySQL NDB Cluster MySQL Connectors Topic Guides. About MySQL Contact Us How to Buy Partners Job Opportunities Site Map.

Рубрика: Driver

на «»

Copyright © 2009. All Rights Reserved.