mysql jdbc连接字符串详解以及属性配置
mysql jdbc连接字符串详解以及属性配置
前言
mysql jdbc 这个虽然使用比较多,但是属性过多,这里做个属性配置收藏。
格式
一般通用的格式为:
protocol//[hosts][/database][?properties]
分别为 协议 连接地址 数据库名 属性配置
常用协议如下
-
jdbc:mysql: is for ordinary and basic JDBC failover connections.
-
jdbc:mysql:loadbalance: is for load-balancing JDBC connections. See Section 9.3, “Configuring Load Balancing with Connector/J” for details.
-
jdbc:mysql:replication: is for JDBC replication connections. See Section 9.4, “Configuring Source/Replica Replication with Connector/J” for details.
-
mysqlx: is for X DevAPI connections.
-
jdbc:mysql+srv: is for ordinary and basic failover JDBC connections that make use of DNS SRV records.
-
jdbc:mysql+srv:loadbalance: is for load-balancing JDBC connections that make use of DNS SRV records.
-
jdbc:mysql+srv:replication: is for replication JDBC connections that make use of DNS SRV records.
-
mysqlx+srv: is for X DevAPI connections that make use of DNS SRV records.
连接地址
肯定有人好奇 不就是个连接地址么,这有什么可说的。
官方文档如下
根据情况,主机部分可能仅由主机名组成,也可以是包含各种元素(如多个主机名、端口号、主机特定属性和用户凭据)的复杂结构。
-
Single host:
Single-host connections without adding host-specific properties:
The hosts part is written in the format of host:port. This is an example of a simple single-host connection URL:
jdbc:mysql://host1:33060/sakila
host can be an IPv4 or an IPv6 host name string, and in the latter case it must be put inside square brackets, for example “[1000:2000::abcd].” When host is not specified, the default value of localhost is used.
host 可以是 IPv4 或 IPv6 主机名字符串,在后一种情况下,它必须放在方括号内,例如“[1000:2000::abcd]”。当未指定 host 时,将使用默认值 localhost。
port is a standard port number, i.e., an integer between 1 and 65535. The default port number for an ordinary MySQL connection is 3306, and it is 33060 for a connection using the X Protocol. If port is not specified, the corresponding default is used.
单主机连接添加主机特定属性:
In this case, the host is defined as a succession of key=value pairs. Keys are used to identify the host, the port, as well as any host-specific properties. There are two alternate formats for specifying keys:
在这种情况下,主机被定义为一系列键=值对。键用于标识主机、端口以及任何特定于主机的属性。有两种替代格式可用于指定键:
The “address-equals” form:
address=(host=host_or_ip)(port=port)(key1=value1)(key2=value2)…(keyN=valueN)
Here is a sample URL using the“address-equals” form :jdbc:mysql://address=(host=myhost)(port=1111)(key1=value1)/db
The “key-value” form:
(host=host,port=port,key1=value1,key2=value2,…,keyN=valueN)
Here is a sample URL using the “key-value” form :jdbc:mysql://address=(host=myhost)(port=1111)(key1=value1)/db
The host and the port are identified by the keys host and port. The descriptions of the format and default values of host and port in Single host without host-specific properties above also apply here.
Other keys that can be added include user, password, protocol, and so on. They override the global values set in the properties part of the URL. Limit the overrides to user, password, network timeouts, and statement and metadata cache sizes; the effects of other per-host overrides are not defined.
Different protocols may require different keys. For example, the mysqlx: scheme uses two special keys, address and priority. address is a host:port pair and priority an integer. For example:
不同的协议可能需要不同的密钥。例如,mysqlx: 方案使用两个特殊密钥,地址和优先级。地址是主机:端口对,优先级是整数。例如:
mysqlx://(address=host:1111,priority=1,key1=value1)/db
key is case-sensitive. Two keys differing in case only are considered conflicting, and there are no guarantees on which one will be used.
-
Multiple hosts
There are two formats for specifying multiple hosts:
List hosts in a comma-separated list:
host1,host2,…,hostN
Each host can be specified in any of the three ways described in Single host above. Here are some examples:jdbc:mysql://myhost1:1111,myhost2:2222/db jdbc:mysql://address=(host=myhost1)(port=1111)(key1=value1),address=(host=myhost2)(port=2222)(key2=value2)/db jdbc:mysql://(host=myhost1,port=1111,key1=value1),(host=myhost2,port=2222,key2=value2)/db jdbc:mysql://myhost1:1111,(host=myhost2,port=2222,key2=value2)/db mysqlx://(address=host1:1111,priority=1,key1=value1),(address=host2:2222,priority=2,key2=value2)/db
List hosts in a comma-separated list, and then encloses the list by square brackets:
[host1,host2,...,hostN]
This is called the host sublist form, which allows sharing of the user credentials by all hosts in the list as if they are a single host. Each host in the list can be specified in any of the three ways described in Single host above. Here are some examples:
jdbc:mysql://sandy:secret@[myhost1:1111,myhost2:2222]/db jdbc:mysql://sandy:secret@[address=(host=myhost1)(port=1111)(key1=value1),address=(host=myhost2)(port=2222)(key2=value2)]/db jdbc:mysql://sandy:secret@[myhost1:1111,address=(host=myhost2)(port=2222)(key2=value2)]/db
While it is not possible to write host sublists recursively, a host list may contain host sublists as its member hosts.
User credentials 用户凭证
User credentials can be set outside of the connection URL—for example, as arguments when getting a connection from the java.sql.DriverManager (see Section 6.3, “Configuration Properties” for details). When set with the connection URL, there are several ways to specify them:
用户凭据可以在连接 URL 之外设置 - 例如,从 java.sql.DriverManager 获取连接时作为参数。当使用连接 URL 设置时,有几种方法可以指定它们:
Prefix the a single host, a host sublist (see Multiple hosts), or any host in a list of hosts with the user credentials with an @:
user:password@host_or_host_sublist
For example:
mysqlx://sandy:secret@[(address=host1:1111,priority=1,key1=value1),(address=host2:2222,priority=2,key2=value2))]/db
Use the keys user and password to specify credentials for each host:
(user=sandy)(password=mypass)
For example:jdbc:mysql://[(host=myhost1,port=1111,user=sandy,password=secret),(host=myhost2,port=2222,user=finn,password=secret)]/db jdbc:mysql://address=(host=myhost1)(port=1111)(user=sandy)(password=secret),address=(host=myhost2)(port=2222)(user=finn)(password=secret)/db
In both forms, when multiple user credentials are specified, the one to the left takes precedence—that is, going from left to right in the connection string, the first one found that is applicable to a host is the one that is used.
在这两种形式中,当指定多个用户凭据时,左侧的凭据优先 - 即,在连接字符串中从左到右,找到的第一个适用于主机的凭据就是使用的凭据。
Inside a host sublist, no host can have user credentials in the @ format, but individual host can have user credentials specified in the key format.
在主机子列表中,没有主机可以具有 @ 格式的用户凭据,但单个主机可以具有以密钥格式指定的用户凭据。
数据库名
这个没啥好说的,就是要连接哪个数据库
属性配置
这有点多 根据不同种类分为以下表格分别描述了属性名称 以及默认值 以及属性出现的版本
常用的有 连接属性配置 会话属性 网络属性 高可用性和集群属性
示例的连接配置 指定了账号密码 连接超时 等配置
jdbc:mysql://hostname:port/databaseName?user=username&password=password&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&maxReconnects=3&retriesAllDown=120&queryTimeoutKillsConnection=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&useUnicode=true&characterSetResults=UTF-8&serverTimezone=Asia/Shanghai
连接属性配置
Name | Default Value | Since Version |
---|---|---|
user | - | all versions |
password | - | all versions |
password1 | - | 8.0.28 |
password2 | - | 8.0.28 |
password3 | - | 8.0.28 |
authenticationPlugins | - | 5.1.19 |
disabledAuthenticationPlugins | - | 5.1.19 |
defaultAuthenticationPlugin | mysql_native_password | 5.1.19 |
ldapServerHostname | - | 8.0.23 |
ociConfigFile | - | 8.0.27 |
ociConfigProfile | DEFAULT | 8.0.33 |
会话属性
Name | Default Value | Since Version |
---|---|---|
sessionVariables | - | 3.1.8 |
characterEncoding | - | 1.1g |
characterSetResults | - | 3.0.13 |
connectionCollation | - | 3.0.13 |
customCharsetMapping | - | 8.0.26 |
trackSessionState | false | 8.0.26 |
网络属性
Name | Default Value | Since Version |
---|---|---|
socksProxyHost | - | 5.1.34 |
socksProxyPort | 1080 | 5.1.34 |
socketFactory | com.mysql.cj.protocol.StandardSocketFactory | 3.0.3 |
connectTimeout | 0 | 3.0.1 |
socketTimeout | 0 | 3.0.1 |
dnsSrv | false | 8.0.19 |
localSocketAddress | - | 5.0.5 |
maxAllowedPacket | 65535 | 5.1.8 |
socksProxyRemoteDns | false | 8.0.29 |
tcpKeepAlive | true | 5.0.7 |
tcpNoDelay | true | 5.0.7 |
tcpRcvBuf | 0 | 5.0.7 |
tcpSndBuf | 0 | 5.0.7 |
tcpTrafficClass | 0 | 5.0.7 |
useCompression | false | 3.0.17 |
安全属性
Name | Default Value | Since Version |
---|---|---|
paranoid | false | 3.0.1 |
serverRSAPublicKeyFile | - | 5.1.31 |
allowPublicKeyRetrieval | false | 5.1.31 |
sslMode | PREFERRED | 8.0.13 |
trustCertificateKeyStoreUrl | - | 5.1.0 |
trustCertificateKeyStoreType | JKS | 5.1.0 |
trustCertificateKeyStorePassword | - | 5.1.0 |
fallbackToSystemTrustStore | true | 8.0.22 |
clientCertificateKeyStoreUrl | - | 5.1.0 |
clientCertificateKeyStoreType | JKS | 5.1.0 |
clientCertificateKeyStorePassword | - | 5.1.0 |
fallbackToSystemKeyStore | true | 8.0.22 |
tlsCiphersuites | - | 5.1.35 |
tlsVersions | - | 8.0.8 |
fipsCompliantJsse | false | 8.1.0 |
KeyManagerFactoryProvider | - | 8.1.0 |
trustManagerFactoryProvider | - | 8.1.0 |
keyStoreProvider | - | 8.1.0 |
sslContextProvider | - | 8.1.0 |
allowLoadLocalInfile | false | 3.0.3 |
allowLoadLocalInfileInPath | - | 8.0.22 |
allowMultiQueries | false | 3.1.1 |
allowUrlInLocalInfile | false | 3.1.4 |
requireSSL | false | 3.1.0 |
useSSL | true | 3.0.2 |
语句属性
Name | Default Value | Since Version |
---|---|---|
cacheDefaultTimeZone | true | 8.0.20 |
continueBatchOnError | true | 3.0.3 |
… | … | … |
预准备语句属性
Name | Default Value | Since Version |
---|---|---|
allowNanAndInf | false | 3.1.5 |
autoClosePStmtStreams | false | 3.1.12 |
compensateOnDuplicateKeyUpdateCounts | false | 5.1.7 |
emulateUnsupportedPstmts | true | 3.1.7 |
generateSimpleParameterMetadata | false | 5.0.5 |
processEscapeCodesForPrepStmts | true | 3.1.12 |
useServerPrepStmts | false | 3.1.0 |
useStreamLengthsInPrepStmts | true | 3.0.2 |
结果集属性
Name | Default Value | Since Version |
---|---|---|
clobberStreamingResults | false | 3.0.9 |
emptyStringsConvertToZero | true | 3.1.8 |
holdResultsOpenOverStatementClose | false | 3.1.7 |
jdbcCompliantTruncation | true | 3.1.2 |
netTimeoutForStreamingResults | 600 | 5.1.0 |
padCharsWithSpace | false | 5.0.6 |
populateInsertRowWithDefaultValues | false | 5.0.5 |
scrollTolerantForwardOnly | false | 8.0.24 |
strictUpdates | true | 3.0.4 |
tinyInt1isBit | true | 3.0.16 |
transformedBitIsBoolean | false | 3.1.9 |
元数据属性
Name | Default Value | Since Version |
---|---|---|
getProceduresReturnsFunctions | true | 5.1.26 |
noAccessToProcedureBodies | false | 5.0.3 |
getProceduresReturnsFunctions | true | 5.1.26 |
noAccessToProcedureBodies | false | 5.0.3 |
nullDatabaseMeansCurrent | false | 3.1.8 |
useHostsInPrivileges | true | 3.0.2 |
useInformationSchema | false | 5.0.0 |
BLOB/CLOB处理属性
Name | Default Value | Since Version |
---|---|---|
blobSendChunkSize | 1048576 | 3.1.9 |
blobsAreStrings | false | 5.0.8 |
clobCharacterEncoding | - | 5.0.0 |
emulateLocators | false | 3.1.0 |
functionsNeverReturnBlobs | false | 5.0.8 |
locatorFetchBufferSize | 1048576 | 3.2.1 |
日期时间类型处理属性
Name | Default Value | Since Version |
---|---|---|
connectionTimeZone | - | 3.0.2 |
forceConnectionTimeZoneToSession | false | 8.0.23 |
preserveInstants | true | 8.0.23 |
sendFractionalSeconds | true | 5.1.37 |
sendFractionalSecondsForTime | true | 8.0.23 |
treatMysqlDatetimeAsTimestamp | false | 8.2.0 |
treatUtilDateAsTimestamp | true | 5.0.5 |
yearIsDateType | true | 3.1.9 |
zeroDateTimeBehavior | EXCEPTION | 3.1.4 |
高可用性和集群属性
Name | Default Value | Since Version |
---|---|---|
autoReconnect | false | 1.1 |
autoReconnectForPools | false | 3.1.3 |
failOverReadOnly | true | 3.0.12 |
maxReconnects | 3 | 1.1 |
reconnectAtTxEnd | false | 3.0.10 |
retriesAllDown | 120 | 5.1.6 |
initialTimeout | 2 | 1.1 |
queriesBeforeRetrySource | 50 | 3.0.2 |
secondsBeforeRetrySource | 30 | 3.0.2 |
allowReplicaDownConnections | false | 6.0.2 |
allowSourceDownConnections | false | 5.1.27 |
ha.enableJMX | false | 5.1.27 |
loadBalanceHostRemovalGracePeriod | 15000 | 6.0.3 |
readFromSourceWhenNoReplicas | false | 6.0.2 |
selfDestructOnPingMaxOperations | 0 | 5.1.6 |
selfDestructOnPingSecondsLifetime | 0 | 5.1.6 |
ha.loadBalanceStrategy | random | 5.0.6 |
性能扩展属性
Name | Default Value | Since Version |
---|---|---|
callableStmtCacheSize | 100 | 3.1.2 |
metadataCacheSize | 50 | 3.1.1 |
alwaysSendSetIsolation | true | 3.1.7 |
maintainTimeStats | true | 3.1.9 |
useCursorFetch | false | 5.0.0 |
cacheCallableStmts | false | 3.1.2 |
cachePrepStmts | false | 3.0.10 |
cacheResultSetMetadata | false | 3.1.1 |
cacheServerConfiguration | false | 3.1.5 |
defaultFetchSize | 0 | 3.1.9 |
dontCheckOnDuplicateKeyUpdateInSQL | false | 5.1.32 |
elideSetAutoCommits | false | 3.1.3 |
enableEscapeProcessing | true |
调试/分析属性
Name | Default Value | Since Version |
---|---|---|
logger | com.mysql.cj.log.StandardLogger | 3.1.1 |
profilerEventHandler | com.mysql.cj.log.LoggingProfilerEventHandler | 5.1.6 |
… | … | … |
异常/警告属性
Name | Default Value | Since Version |
---|---|---|
dumpQueriesOnException | false | 3.1.3 |
exceptionInterceptors | - | 5.1.8 |
… | … | … |
与其他产品集成调整属性
Name | Default Value | Since Version |
---|---|---|
overrideSupportsIntegrityEnhancementFacility | false | 3.1.12 |
ultraDevHack | false | 2.0.3 |
JDBC合规性属性
Name | Default Value | Since Version |
---|---|---|
useColumnNamesInFindColumn | false | 5.1.7 |
pedantic | false | 3.0.0 |
useOldAliasMetadataBehavior | false | 5.0.4 |
X协议和X DevAPI属性
Name | Default Value | Since Version |
---|---|---|
xdevapi.auth | PLAIN | 8.0.8 |
xdevapi.compression | PREFERRED | 8.0.20 |
xdevapi.compression-algorithms | zstd_stream,lz4_message,deflate_stream | 8.0.22 |
xdevapi.compression-extensions | - | 8.0.22 |
xdevapi.connect-timeout | 10000 | 8.0.13 |
xdevapi.connection-attributes | - | 8.0.16 |
xdevapi.dns-srv | false | 8.0.19 |
xdevapi.fallback-to-system-keystore | true | 8.0.22 |
xdevapi.fallback-to-system-truststore | true | 8.0.22 |
xdevapi.ssl-keystore | - | 8.0.22 |
xdevapi.ssl-keystore-password | - | 8.0.22 |
xdevapi.ssl-keystore-type | JKS | 8.0.22 |
xdevapi.ssl-mode | REQUIRED | 8.0.7 |
xdevapi.ssl-truststore | - | 6.0.6 |
xdevapi.ssl-truststore-password | - | 6.0.6 |
xdevapi.ssl-truststore-type | JKS | 6.0.6 |
xdevapi.tls-ciphersuites | - | 8.0.19 |
xdevapi.tls-versions | - | 8.0.19 |
参考文档:
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-jdbc-url-format.html
https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)