Partager via


Interroger MySQL avec Azure Databricks

Cet exemple interroge MySQL par le biais de son pilote JDBC. Pour plus d’informations sur la lecture, l’écriture, la configuration du parallélisme et le pushdown des requêtes, voir Bases de données de requête à l’aide de JDBC.

Notes

Vous pouvez préférer Lakehouse Federation pour gérer les requêtes vers MySQL. Consultez Qu’est-ce que la Fédération Lakehouse.

Utilisation de JDBC

Python

driver = "com.mysql.cj.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()
)

Scala

val driver = "com.mysql.cj.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()

Utilisation du connecteur MySQL dans Databricks Runtime

À l’aide de Databricks Runtime 11.3 LTS et versions ultérieures, vous pouvez utiliser le connecteur nommé pour interroger MySQL. Regardez les exemples suivants :

Python

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()
)

SQL

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;

Scala

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()