閱讀英文

共用方式為

使用 Azure Databricks 查询 SQL Server

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

重要

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

配置与 SQL Server 的连接

在 Databricks Runtime 11.3 LTS 及更高版本中,可以使用 sqlserver 关键字通过随附的驱动程序连接到 SQL Server。 使用数据帧时,请使用以下语法:

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 时,请在 USING 子句中指定 sqlserver 并在创建表时传递选项,如以下示例所示:

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 设置来指定驱动程序和配置。 以下示例使用 SQL Server 的 JDBC 驱动程序对其进行查询。 有关读取、写入、配置并行度和查询下推的更多详细信息,请参阅使用 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()