A truly async MySQL ADO.NET provider, supporting MySQL Server, MariaDB, Amazon Aurora, Azure Database for MySQL, Google Cloud SQL, and more.
$ dotnet add package MySqlConnectorMySqlConnector is a C# ADO.NET driver for MySQL, MariaDB, Amazon Aurora, Azure Database for MySQL and other MySQL-compatible databases.
More documentation is available at the MySqlConnector website.
// set these values correctly for your database server
var builder = new MySqlConnectionStringBuilder
{
Server = "your-server",
UserID = "database-user",
Password = "P@ssw0rd!",
Database = "database-name",
};
// open a connection asynchronously
await using var connection = new MySqlConnection(builder.ConnectionString);
await connection.OpenAsync();
// create a DB command and set the SQL statement with parameters
await using var command = connection.CreateCommand();
command.CommandText = @"SELECT * FROM orders WHERE order_id = @OrderId;";
command.Parameters.AddWithValue("@OrderId", orderId);
// execute the command and read the results
await using var reader = await command.ExecuteReaderAsync();
while (reader.Read())
{
var id = reader.GetInt32("order_id");
var date = reader.GetDateTime("order_date");
// ...
}
For ASP.NET, use the MySqlConnector.DependencyInjection package to integrate with dependency injection and logging.
var builder = WebApplication.CreateBuilder(args);
// use AddMySqlDataSource to configure MySqlConnector
builder.Services.AddMySqlDataSource(builder.Configuration.GetConnectionString("Default"));
var app = builder.Build();
// use dependency injection to get a MySqlConnection in minimal APIs or in controllers
app.MapGet("/", async (MySqlConnection connection) =>
{
// open and use the connection here
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT name FROM users LIMIT 1";
return "Hello World: " + await command.ExecuteScalarAsync();
});
app.Run();
The main types provided by this library are:
MySqlConnection (implementation of DbConnection)MySqlCommand (implementation of DbCommand)MySqlDataReader (implementation of DbDataReader)MySqlBulkCopyMySqlBulkLoaderMySqlConnectionStringBuilderMySqlConnectorFactoryMySqlDataAdapterMySqlExceptionMySqlTransaction (implementation of DbTransaction)MySqlConnector is released as open source under the MIT license. Bug reports and contributions are welcome at the GitHub repository.