Spring Boot JDBCTemplate连接Azure SQL遇TCP/IP及连接字符串问题
问题现象
本地SQL数据库连接正常,但连接Azure SQL时,无论是通过@Autowired配合application.properties配置,还是手动配置DataSource Bean,均无法成功连接并报错。
报错信息
The TCP/IP connection to the host tcp:food-server.database.windows.net, port 1433 has failed.
Error: "tcp:food-server.database.windows.net. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall."
尝试过的连接方式
方式1:通过application.properties自动装配
spring.datasource.url= jdbc:sqlserver://tcp:food-server.database.windows.net,1433;encrypt=true;trustServerCertificate=true;databaseName=Test spring.datasource.username=sauser spring.datasource.password=password12345*
方式2:手动配置DataSource Bean
@Configuration public class ServerConfiguration { @Bean public DataSource getDataSource() { SQLServerDataSource ds = new SQLServerDataSource(); ds.setUser("sauser"); ds.setPassword("password12345*"); ds.setServerName("tcp:food-server.database.windows.net"); ds.setPortNumber(1433); ds.setTrustServerCertificate(true); ds.setDatabaseName("test"); return ds; } @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate() { return new NamedParameterJdbcTemplate(getDataSource()); } }
已完成的配置
已在Azure SQL门户的数据库防火墙设置中添加了本地IP地址的访问权限。
排查与解决方案
1. 修正连接字符串格式
方式1的URL存在格式错误:jdbc:sqlserver://后无需重复tcp:前缀,端口分隔符应使用:而非,,且Azure SQL强制加密场景下不建议开启trustServerCertificate=true,正确配置如下:
spring.datasource.url=jdbc:sqlserver://food-server.database.windows.net:1433;encrypt=true;trustServerCertificate=false;databaseName=Test spring.datasource.username=sauser spring.datasource.password=password12345*
2. 修正手动配置的ServerName
方式2中setServerName不应包含tcp:前缀,同时调整证书信任配置,修正后代码:
@Configuration public class ServerConfiguration { @Bean public DataSource getDataSource() { SQLServerDataSource ds = new SQLServerDataSource(); ds.setUser("sauser"); ds.setPassword("password12345*"); ds.setServerName("food-server.database.windows.net"); ds.setPortNumber(1433); ds.setTrustServerCertificate(false); ds.setDatabaseName("test"); return ds; } @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate() { return new NamedParameterJdbcTemplate(getDataSource()); } }
3. 额外排查点
- 测试本地网络连通性:用
telnet food-server.database.windows.net 1433或Test-NetConnection food-server.database.windows.net -Port 1433确认1433端口未被本地防火墙/代理拦截。 - 检查Azure防火墙规则:确保添加的是服务器级防火墙规则,而非仅数据库级;若本地是动态IP,需重新获取当前公网IP并更新规则。
- 验证用户名格式:Azure SQL用户名需完整格式
username@servername(例如sauser@food-server),部分场景下需此格式才能完成认证。 - 更新JDBC驱动:确保使用最新版mssql-jdbc驱动(推荐12.x及以上版本),避免驱动兼容性问题。
内容的提问来源于stack exchange,提问作者mattsmith5

