SQL DW的JDBC连接字符串



如何使用JDBC连接字符串中的访问令牌连接到Azure SQL DW?

请参考本Azure教程:使用访问令牌进行连接:

  • 应用程序/服务可以从Azure中检索访问令牌Active Directory并使用它连接到Azure SQL数据库/数据仓库

下面的示例包含一个简单的Java应用程序,该应用程序使用基于访问令牌的身份验证连接到Azure SQL数据库/数据仓库。

代码示例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
// The azure-activedirectory-library-for-java is needed to retrieve the access token from the AD.
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
public class AADTokenBased {
public static void main(String[] args) throws Exception {
// Retrieve the access token from the AD.
String spn = "https://database.windows.net/";
String stsurl = "https://login.microsoftonline.com/..."; // Replace with your STS URL.
String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
String clientSecret = "..."; // Replace with your client secret.
AuthenticationContext context = new AuthenticationContext(stsurl, false, Executors.newFixedThreadPool(1));
ClientCredential cred = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken(spn, cred, null);
String accessToken = future.get().getAccessToken();
System.out.println("Access Token: " + accessToken);
// Connect with the access token.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name.
ds.setDatabaseName("demo"); // Replace with your database name.
ds.setAccessToken(accessToken);
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));
}
}
}
}

HTH。

最新更新