使用 Azure Databricks 查询 SQL Server

重要

旧查询联合文档已停用,可能不会更新。 此内容中提到的产品、服务或技术未经 Databricks 正式认可或测试。 请参见什么是 Lakehouse 联盟?

本文介绍如何将 Azure Databricks 连接到 Microsoft SQL Server 以读取和写入数据。

重要

本文所述的配置为试验性配置。 试验性功能按原样提供,Databricks 不会通过客户技术支持为它提供支持。 为了获得完整的查询联邦支持,您应该改为使用 Lakehouse Federation,这使 Azure Databricks 的用户能够利用 Unity Catalog 语法和数据治理工具。

配置与 SQL Server 的连接

在 Databricks Runtime 11.3 LTS 及更高版本中,可以使用关键字来使用 sqlserver 包含的驱动程序连接到 SQL Server。 使用 DataFrame 时,请使用以下语法:

Python语言

remote_table = (spark.read
  .format("sqlserver")
  .option("host", "hostName")
  .option("port", "port") # optional, can use default port 1433 if omitted
  .option("user", "username")
  .option("password", "password")
  .option("database", "databaseName")
  .option("dbtable", "schemaName.tableName") # (if schemaName not provided, default to "dbo")
  .load()
)

Scala(编程语言)

val remote_table = spark.read
  .format("sqlserver")
  .option("host", "hostName")
  .option("port", "port") // optional, can use default port 1433 if omitted
  .option("user", "username")
  .option("password", "password")
  .option("database", "databaseName")
  .option("dbtable", "schemaName.tableName") // (if schemaName not provided, default to "dbo")
  .load()

使用 SQL 时,在sqlserver子句中指定USING,并在创建表时传递选项,如以下示例所示:

DROP TABLE IF EXISTS sqlserver_table;
CREATE TABLE sqlserver_table
USING sqlserver
OPTIONS (
  dbtable '<schema-name.table-name>',
  host '<host-name>',
  port '1433',
  database '<database-name>',
  user '<username>',
  password '<password>'
);

使用旧版 JDBC 驱动程序

在 Databricks Runtime 10.4 LTS 及更低版本中,必须使用 JDBC 设置指定驱动程序和配置。 以下示例使用其 JDBC 驱动程序查询 SQL Server。 有关读取、写入、配置并行度和查询下推的更多详细信息,请参阅 使用 JDBC 的查询数据库

Python语言

driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"

database_host = "<database-host-url>"
database_port = "1433" # update if you use a non-default port
database_name = "<database-name>"
table = "<table-name>"
user = "<username>"
password = "<password>"

url = f"jdbc:sqlserver://{database_host}:{database_port};database={database_name}"

remote_table = (spark.read
  .format("jdbc")
  .option("driver", driver)
  .option("url", url)
  .option("dbtable", table)
  .option("user", user)
  .option("password", password)
  .load()
)

Scala(编程语言)

val driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"

val database_host = "<database-host-url>"
val database_port = "1433" // update if you use a non-default port
val database_name = "<database-name>"
val table = "<table-name>"
val user = "<username>"
val password = "<password>"

val url = s"jdbc:sqlserver://{database_host}:{database_port};database={database_name}"

val remote_table = spark.read
  .format("jdbc")
  .option("driver", driver)
  .option("url", url)
  .option("dbtable", table)
  .option("user", user)
  .option("password", password)
  .load()