如何使用 JDBC 驱动程序连接到名称中带有重音符号的 SQL 服务器?

How to connect to SQL Server with accent in name using JDBC driver?

我一直在尝试将 Spring 引导应用程序连接到我的本地 SQL 服务器,但是由于服务器名称包含重音字符(即 É),连接协议似乎不允许。

我已经尝试指定 useUnicodecharacterEncoding 属性,但到目前为止没有任何效果。

这是 application.properties 文件:

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

#connection using Windows Authentication
spring.datasource.url=jdbc:sqlserver://FLÉK\MSSQLSERVER02;databasename=MyDatabase;integratedSecurity=true;useUnicode=true;characterEncoding=UTF-8
spring.datasource.username=usname
spring.datasource.password=somepassword

错误信息:

com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host FL�K, named instance mssqlserver02 failed. Error: "java.net.UnknownHostException: FL�K". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434.  For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.

我无法更改服务器名称,因为这需要重新安装服务器本身。有什么想法我应该在什么级别寻找解决方案,或者我应该在哪里启用 unicode 的使用?

Java .properties 文件默认为 ISO-8859-1 字符集,但看起来您保存为 UTF-8。见 Properties.load(InputStream):

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

您在 Java 中通常有两个选项:

  1. 明确保存在 ISO-8859-1 中。这是一种非常脆弱的方法,因为它只需要一个编辑器自动 'fixing' 东西并保存为 UTF-8 以重新引入问题
  2. 对 ASCII 范围之外的字符使用 Unicode 转义符,在本例中为 \u00c9

对于 Spring 具体而言,您还有第三种选择

  1. 切换到使用默认为 UTF-8 的 YAML 配置文件。

对于一般的 Java,而不是 Spring 应用程序属性,您还可以选择使用 Properties.load(Reader) 加载属性文件,其中 reader已使用文件的正确字符集构建。