根据我的测试,如果要连接Azure SQL本地机器,请参考以下步骤
- 创建服务主体
az ad sp create-for-rbac -n 'name' --skip-assignment
将服务主体添加为 Azure SQL 数据库包含的用户。
设置环境变量。请设置以下变量为环境变量
AZURE_TENANT_ID: ID of the service principal's tenant. Also called its 'directory' ID.
AZURE_CLIENT_ID: the service principal's client ID
AZURE_CLIENT_SECRET: one of the service principal's client secrets
- SDK
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
- 代码
public static void main( String[] args )
{
AccessToken token= GetAccessToken();
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("<>.database.windows.net"); // Replace with your server name.
ds.setDatabaseName("demo"); // Replace with your database name.
ds.setAccessToken(token.getToken());
try (Connection connection = ds.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
if (rs.next()) {
System.out.println("You have successfully logged on as: " + rs.getString(1));
}
}
}
public static AccessToken GetAccessToken() {
DefaultAzureCredential creds = new DefaultAzureCredentialBuilder()
.build();
TokenRequestContext request = new TokenRequestContext();
System.out.println("444");
request.addScopes("https://database.windows.net//.default");
String token;
AccessToken accesstoken=creds.getToken(request).block();
return accesstoken;
}