Connect to MySQL
Bu içerik henüz dilinizde mevcut değil.
This page describes how consuming apps connect to a MySQL resource that’s already modeled in your AppHost. For the AppHost API surface — adding a MySQL server, databases, phpMyAdmin, volumes, init files, and more — see MySQL Hosting integration.
When you reference a MySQL resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire MySQL client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called mysqldb becomes MYSQLDB_URI.
MySQL server
Section titled “MySQL server”The MySQL server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the MySQL server |
Port | The port number the MySQL server is listening on |
Username | The username for authentication (root by default) |
Password | The password for authentication |
Uri | The connection URI in mysql:// format, with the format mysql://{Username}:{Password}@{Host}:{Port} |
JdbcConnectionString | JDBC-format connection string, with the format jdbc:mysql://{Host}:{Port}. User and password credentials are provided as separate Username and Password properties. |
Example connection strings:
Uri: mysql://root:p%40ssw0rd1@localhost:3306JdbcConnectionString: jdbc:mysql://localhost:3306MySQL database
Section titled “MySQL database”The MySQL database resource inherits all properties from its parent server resource and adds:
| Property Name | Description |
|---|---|
Uri | The connection URI with the database name, with the format mysql://{Username}:{Password}@{Host}:{Port}/{DatabaseName} |
JdbcConnectionString | JDBC connection string with database name, with the format jdbc:mysql://{Host}:{Port}/{DatabaseName}. User and password credentials are provided as separate Username and Password properties. |
DatabaseName | The name of the database |
Example connection strings:
Uri: mysql://root:p%40ssw0rd1@localhost:3306/mysqldbJdbcConnectionString: jdbc:mysql://localhost:3306/mysqldbConnect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds a MySQL database resource named mysqldb and references it from the consuming app.
For C# apps, the recommended approach is the Aspire MySQL client integration. It registers a MySqlDataSource through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.MySqlConnector NuGet package in the client-consuming project:
dotnet add package Aspire.MySqlConnector#:package Aspire.MySqlConnector@*<PackageReference Include="Aspire.MySqlConnector" Version="*" />Add the MySQL data source
Section titled “Add the MySQL data source”In Program.cs, call AddMySqlDataSource on your IHostApplicationBuilder to register a MySqlDataSource:
builder.AddMySqlDataSource(connectionName: "mysqldb");Resolve the data source through dependency injection:
public class ExampleService(MySqlDataSource dataSource){ // Use dataSource...}Add keyed MySQL data sources
Section titled “Add keyed MySQL data sources”To register multiple MySqlDataSource instances with different connection names, use AddKeyedMySqlDataSource:
builder.AddKeyedMySqlDataSource(name: "mainDb");builder.AddKeyedMySqlDataSource(name: "loggingDb");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("mainDb")] MySqlDataSource mainDataSource, [FromKeyedServices("loggingDb")] MySqlDataSource loggingDataSource){ // Use data sources...}For more information on keyed services, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire MySQL client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddMySqlDataSource:
builder.AddMySqlDataSource("mysqldb");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "mysqldb": "Server=mysql;Database=mysqldb" }}For more information, see MySqlConnector: ConnectionString documentation.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MySqlConnectorSettings from appsettings.json (or any other configuration source) by using the Aspire:MySqlConnector key:
{ "Aspire": { "MySqlConnector": { "ConnectionString": "Server=mysql;Database=mysqldb", "DisableHealthChecks": false, "DisableTracing": false, "DisableMetrics": false } }}For the complete MySQL client integration JSON schema, see Aspire.MySqlConnector/ConfigurationSchema.json.
Inline delegates. Pass an Action<MySqlConnectorSettings> to configure settings inline, for example to disable health checks:
builder.AddMySqlDataSource( "mysqldb", static settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The MySQL client integration adds:
- A health check that verifies a connection can be made and commands can be executed against the MySQL database.
- Integration with the
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire MySQL client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
MySqlConnector.ConnectionPoolMySqlConnector.MySqlBulkCopyMySqlConnector.MySqlCommandMySqlConnector.MySqlConnectionMySqlConnector.MySqlDataSource
Tracing activities:
MySqlConnector
Metrics:
db.client.connections.create_timedb.client.connections.use_timedb.client.connections.wait_timedb.client.connections.idle.maxdb.client.connections.idle.mindb.client.connections.maxdb.client.connections.pending_requestsdb.client.connections.timeoutsdb.client.connections.usage
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and connect using the 📦 MySqlConnector NuGet package directly:
using MySqlConnector;
var connectionString = Environment.GetEnvironmentVariable("MYSQLDB_URI");
await using var dataSource = MySqlDataSource.Create(connectionString!);await using var conn = await dataSource.OpenConnectionAsync();
// Use conn to query the database...Use go-sql-driver/mysql, the most widely used MySQL driver for Go:
go get github.com/go-sql-driver/mysqlRead the injected environment variables and connect:
package main
import ( "database/sql" "fmt" "os"
_ "github.com/go-sql-driver/mysql")
func main() { // Read Aspire-injected connection properties host := os.Getenv("MYSQLDB_HOST") port := os.Getenv("MYSQLDB_PORT") user := os.Getenv("MYSQLDB_USERNAME") password := os.Getenv("MYSQLDB_PASSWORD") dbName := os.Getenv("MYSQLDB_DATABASE")
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, host, port, dbName)
db, err := sql.Open("mysql", dsn) if err != nil { panic(err) } defer db.Close()
if err := db.Ping(); err != nil { panic(err) }}Install a MySQL driver. This example uses mysql-connector-python, the official Oracle connector:
pip install mysql-connector-pythonRead the injected environment variables and connect:
import osimport mysql.connector
# Read Aspire-injected connection propertiesconn = mysql.connector.connect( host=os.getenv("MYSQLDB_HOST"), port=int(os.getenv("MYSQLDB_PORT", "3306")), user=os.getenv("MYSQLDB_USERNAME"), password=os.getenv("MYSQLDB_PASSWORD"), database=os.getenv("MYSQLDB_DATABASE"),)
cursor = conn.cursor()# Use cursor to query the database...cursor.close()conn.close()Install mysql2, a fast and modern MySQL client for Node.js with Promise support:
npm install mysql2Read the injected environment variables and connect:
import mysql from 'mysql2/promise';
// Read Aspire-injected connection propertiesconst connection = await mysql.createConnection({ host: process.env.MYSQLDB_HOST, port: Number(process.env.MYSQLDB_PORT), user: process.env.MYSQLDB_USERNAME, password: process.env.MYSQLDB_PASSWORD, database: process.env.MYSQLDB_DATABASE,});
// Use connection to query the database...await connection.end();Or use the connection URI directly:
import mysql from 'mysql2/promise';
const connection = await mysql.createConnection(process.env.MYSQLDB_URI!);
// Use connection to query the database...await connection.end();For connection pooling (recommended in production), use createPool instead:
import mysql from 'mysql2/promise';
const pool = mysql.createPool({ host: process.env.MYSQLDB_HOST, port: Number(process.env.MYSQLDB_PORT), user: process.env.MYSQLDB_USERNAME, password: process.env.MYSQLDB_PASSWORD, database: process.env.MYSQLDB_DATABASE, waitForConnections: true, connectionLimit: 10,});
// Use pool to query the database...