Microsoft Docs - Building the Connection URL
连接 URL 中的转义值
由于包含空格、分号和引号等特殊字符,您可能必须转义连接 URL 值的某些部分。如果这些字符括在大括号中,则 JDBC 驱动程序支持对它们进行转义。例如,{;} 转义分号。
转义值可以包含特殊字符(尤其是“=”、“;”、“[]”和空格),但不能包含大括号。必须转义并包含大括号的值应添加到属性集合中。
因此更改密码或将用户/密码另存为单独的变量并将其添加到连接中。
String dbURL = "jdbc:sqlserver://localhost\\sqlexpress";
String user = "sa";
String pass = "secret";
conn = DriverManager.getConnection(dbURL, user, pass);
如果您想使用属性集合,您可以在此处找到属性名称:
Microsoft Docs - Setting the Connection Properties
java2s - Create Connection With Properties 有一个很好的 java 示例。它适用于 MySQL 服务器,但您只需更改属性名称。 (来自上面的链接页面)
tl;博士
潜入源头
SourceCode - DriverManager.java
使用.getConnection(String url, String user, String password) 将创建一个Properties 条目。
@CallerSensitive
public static Connection getConnection(String url,
String user, String password) throws SQLException {
java.util.Properties info = new java.util.Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
return (getConnection(url, info, Reflection.getCallerClass()));
}
mssql-jdbc 代码
MSSQL-JDBC - SQLServerDriver.java
public java.sql.Connection connect(String Url, Properties suppliedProperties)
用途:
// Merge connectProperties (from URL) and supplied properties from user.
Properties connectProperties = parseAndMergeProperties(Url, suppliedProperties);
从给定的 connectionUrl 中获取(额外的)属性:
private Properties parseAndMergeProperties(String Url, Properties suppliedProperties)
正在使用:
Properties connectProperties = Util.parseUrl(Url, drLogger);
在MSSQL- Util.java
是破坏者。
if (ch == ';') {...}
case inEscapedValueStart:
if (ch == '}') {...}
case inEscapedValueEnd:
if (ch == ';') {...}
绕过此案例切换并直接进入“SQLServerConnection.java”的唯一方法是提供正确的属性集合!
MSSQL-JDBC - SQLServerConnection.java
函数Connection connect(Properties propsIn, SQLServerPooledConnection pooledConnection)
分别Connection connectInternal(Properties propsIn, SQLServerPooledConnection pooledConnection):
sPropKey = SQLServerDriverStringProperty.PASSWORD.toString();
sPropValue = activeConnectionProperties.getProperty(sPropKey);
if (sPropValue == null) {
sPropValue = SQLServerDriverStringProperty.PASSWORD.getDefaultValue();
activeConnectionProperties.setProperty(sPropKey, sPropValue);
}