using MySql.Data.MySqlClient; // ... public async TaskGetNumberOfUsersAsync() { using var connection = new MySqlConnection("connectionString"); await connection.OpenAsync(); var command = new MySqlCommand("SELECT COUNT(*) FROM Users", connection); var result = await command.ExecuteScalarAsync(); return (int)result; }
using MySql.Data.MySqlClient; // ... public async TaskIn this example, we use `ExecuteScalarAsync` to get the last name of a user with a specific ID in a MySQL database. We create a new `MySqlCommand` object with the SQL query `SELECT LastName FROM Users WHERE Id = @id`, set the value of the parameter @id to the userId parameter, and then call `ExecuteScalarAsync` to execute the command and get the result. The `MySqlCommand` class is part of the MySql.Data NuGet package.GetLastNameAsync(int userId) { using var connection = new MySqlConnection("connectionString"); await connection.OpenAsync(); var command = new MySqlCommand("SELECT LastName FROM Users WHERE Id = @id", connection); command.Parameters.AddWithValue("@id", userId); var result = await command.ExecuteScalarAsync(); return (string)result; }