To work with a MySQL (or MariaDB) database from C#, install an ADO.NET driver from NuGet, open a connection and run parameterised commands. The examples below use MySqlConnector, an MIT-licensed driver with true async I/O:
dotnet add package MySqlConnector
Oracle’s own driver, MySql.Data, works too and has almost the same API (MySqlConnection, MySqlCommand, Parameters.AddWithValue). Change the using to MySql.Data.MySqlClient and most of the code below compiles unchanged. I prefer MySqlConnector because its async methods really are asynchronous, it is faster under load, and it has no GPL licensing questions.
The sample table
CREATE TABLE Customers (
Id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(100) NOT NULL
);
Keep the connection string out of the code
The connection string contains a password, so read it from configuration rather than hard-coding it. In a console app an environment variable is the simplest option; in ASP.NET Core use appsettings.json plus user secrets or a vault. The value looks like Server=localhost;Database=mydb;User ID=app_user;Password=....
Full example
using MySqlConnector;
string connectionString = Environment.GetEnvironmentVariable("MYSQL_CONNECTION")
?? throw new InvalidOperationException("Set the MYSQL_CONNECTION environment variable.");
await using var connection = new MySqlConnection(connectionString);
await connection.OpenAsync();
long id = await InsertCustomerAsync(connection, "Bill Gates");
await UpdateCustomerAsync(connection, id, "William Gates");
await PrintCustomersAsync(connection);
await DeleteCustomerAsync(connection, id);
static async Task PrintCustomersAsync(MySqlConnection connection)
{
await using var command = new MySqlCommand(
"SELECT Id, Name FROM Customers ORDER BY Id LIMIT 10", connection);
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine($"{reader.GetInt32(0)}: {reader.GetString(1)}");
}
}
static async Task<long> InsertCustomerAsync(MySqlConnection connection, string name)
{
await using var command = new MySqlCommand(
"INSERT INTO Customers (Name) VALUES (@name)", connection);
command.Parameters.AddWithValue("@name", name);
await command.ExecuteNonQueryAsync();
return command.LastInsertedId;
}
static async Task<int> UpdateCustomerAsync(MySqlConnection connection, long id, string name)
{
await using var command = new MySqlCommand(
"UPDATE Customers SET Name = @name WHERE Id = @id", connection);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@id", id);
return await command.ExecuteNonQueryAsync();
}
static async Task<int> DeleteCustomerAsync(MySqlConnection connection, long id)
{
await using var command = new MySqlCommand(
"DELETE FROM Customers WHERE Id = @id", connection);
command.Parameters.AddWithValue("@id", id);
return await command.ExecuteNonQueryAsync();
}
ExecuteNonQueryAsync returns the number of affected rows, so an update or delete that returns 0 did not find its row. LastInsertedId holds the AUTO_INCREMENT value generated by the insert, which saves a separate SELECT LAST_INSERT_ID() round trip.
If you need a DataTable, for example to bind to a WinForms grid, load it straight from the reader with table.Load(reader).
Always use parameters
The original version of this post built a DELETE statement by gluing strings together. Do not do that. With parameters, the value travels separately from the SQL text, so input such as '; DROP TABLE Customers; -- is stored as a harmless string. Parameters also take care of quoting, decimal separators and date formats, which otherwise vary with the culture of the machine.
Parameters cannot replace identifiers. If a table or column name has to be dynamic, pick it from a fixed list in your code and never from user input.
Transactions
When several statements must succeed or fail together, run them in a transaction:
static async Task RenameCustomerAndBookAsync(MySqlConnection connection)
{
await using var transaction = await connection.BeginTransactionAsync();
await using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "UPDATE Customers SET Name = @name WHERE Id = @id";
command.Parameters.AddWithValue("@name", "Bill Gates");
command.Parameters.AddWithValue("@id", 1);
await command.ExecuteNonQueryAsync();
command.CommandText = "UPDATE Books SET Title = @title WHERE Id = @id";
command.Parameters.Clear();
command.Parameters.AddWithValue("@title", "New Title");
command.Parameters.AddWithValue("@id", 2);
await command.ExecuteNonQueryAsync();
await transaction.CommitAsync();
}
There is no explicit rollback. If either command throws, the transaction is disposed without being committed, and disposing an uncommitted transaction rolls it back. That is simpler and safer than the old catch { tr.Rollback(); } pattern, which crashed with a NullReferenceException when the failure happened before the transaction was created.
MySqlConnector is strict about one thing: every command that runs while a transaction is open must have its Transaction property set, or it throws an InvalidOperationException. MySql.Data silently lets you forget. Transactions also need a transactional storage engine; InnoDB, the default, is fine, while MyISAM ignores them.
Connections and pooling
Opening a connection is cheap because the driver pools them. In a web app, open a connection per request or per unit of work and dispose it quickly with await using. Do not keep one connection in a static field and share it between threads: a MySqlConnection can only run one command at a time.
Thanks, it was useful
Thanks for finally writing about >Select,Insert,Update,Delete Data in MySQL using C# | C# Examples <Liked it!