Consultar MySQL com Databricks

Este exemplo query o MySQL usando seu driver JDBC. Para obter mais detalhes sobre leitura, gravação, configuração de paralelismo e empilhamento query , consulte query bancos de dados usando JDBC.

Observação

O senhor pode preferir o lakehouse Federation para gerenciar as consultas ao MySQL. Veja o que é lakehouse Federation.

Usando JDBC

driver = "org.mariadb.jdbc.Driver"

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

url = f"jdbc:mysql://{database_host}:{database_port}/{database_name}"

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

val database_host = "<database-host-url>"
val database_port = "3306" # 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:mysql://${database_host}:${database_port}/${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()

Usando o conector MySQL no Databricks Runtime

Usando o Databricks Runtime 11.2 LTS e acima, você pode usar o conector nomeado para query o MySQL. Veja os seguintes exemplos:

remote_table = (spark.read
  .format("mysql")
  .option("dbtable", "table_name")
  .option("host", "database_hostname")
  .option("port", "3306") # Optional - will use default port 3306 if not specified.
  .option("database", "database_name")
  .option("user", "username")
  .option("password", "password")
  .load()
)
DROP TABLE IF EXISTS mysql_table;
CREATE TABLE mysql_table
USING mysql
OPTIONS (
  dbtable '<table-name>',
  host '<database-host-url>',
  port '3306', /* Optional - will use default port 3306 if not specified. */
  database '<database-name>',
  user '<username>',
  password '<password>'
);
SELECT * from mysql_table;
val remote_table = spark.read
  .format("mysql")
  .option("dbtable", "table_name")
  .option("host", "database_hostname")
  .option("port", "3306") # Optional - will use default port 3306 if not specified.
  .option("database", "database_name")
  .option("user", "username")
  .option("password", "password")
  .load()