This is an example how to use it:
public static void Create(Cliente entity)
{
using (var cn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()) )
{
cn.Open();
using (var cmd = cn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO Clientes(RazonSocial, DocumentoIdentidad, NumeroDocumento, Direccion, Telefono)" +
" VALUES(?RazonSocial, ?DocumentoIdentidad, ?NumeroDocumento, ?Direccion, ?Telefono)";
cmd.Parameters.AddWithValue("?RazonSocial", entity.RazonSocial);
cmd.Parameters.AddWithValue("?DocumentoIdentidad", entity.DocumentoIdentidad);
cmd.Parameters.AddWithValue("?NumeroDocumento", entity.NumeroDocumento);
cmd.Parameters.AddWithValue("?Direccion", entity.Direccion);
cmd.Parameters.AddWithValue("?Telefono", entity.Telefono);
cmd.ExecuteNonQuery();
}
}
}
Answering your question:
By enclosing the declaration of the object Connection
between a block Using
... End Using
, we will be sure to close the connection and destroy the resources used by the object, at the end of that block (when it is executed End Using
). With this we do not have to be aware of calling the method Close
(to close the connection), nor the method Dispose
(to destroy the object), therefore, it is not necessary to have an external procedure for such tasks.
If you go inside a class? If you can put it inside a class to avoid mixing the code. It is advisable to work in layers: Presence, Logic, Persistence, Entities. Each layer has a responsibility.
-
Presentation: Responsible for interacting with the user
-
Logic: Responsible for calling methods and business logic
-
Persistence: Persist against the database
-
Entities: Mappings to data
Each layer has a responsibility and can not be contaminated with responsibilities from other layers.