How can I connect to the Mysql database and make queries? For example in PHP, I connect like this

$db_host = "localhost"; $db_user = "root"; $db_password = ""; $db_name = "table"; $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); 

And then I make a request for information on the ID

 $query = mysqli_query($mysqli, "SELECT * FROM `users` WHERE `Id` = '"$id"'"); $user = mysqli_fetch_assoc($query); 

And then I use it like this

 $email = $user["Email"]; $name = $user["Name"]; 

On the Internet I can not find a clear connection and information, as in PHP.

    1 answer 1

    To connect to MySql in C #, use the MySql.Data library ( MySql Connector / NET ) for example.


    Example

    Add namespace

     using MySql.Data.MySqlClient; 

    Then create a connection string using the class MySqlConnectionStringBuilder

     MySqlConnectionStringBuilder stringBuilder = new MySqlConnectionStringBuilder(); stringBuilder.Server = "localhost"; stringBuilder.UserID = "root"; stringBuilder.Password = ""; stringBuilder.Database = "table"; string connectionString = stringBuilder.ToString(); 

    Then create a connection to MySql.

     MySqlConnection connection = new MySqlConnection(connectionString); 

    Create a command and install the SQL query.

     uint id = 0; MySqlCommand command = connection.CreateCommand(); command.CommandText = "SELECT * FROM `users` WHERE `id` = @id"; command.Parameters.AddWithValue("@id", id); // Заметьте, можно использовать параметры. 

    Open the connection, call MySqlDataReader and read the result.

     connection.Open(); string name = null; string email = null; using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) // reader.Read() возвращает true и переходит к следующему ряду. { name = reader.GetString("Name"); email = reader.GetString("Email"); } } connection.Close();