简体   繁体   中英

Query on Mysql database with asp.net core

I need to query the database. This query is working correctly, but I need to loop to read all data in the table. I don't know how to put "do" or "while" in this query

[HttpPost]
public IActionResult SendMessage(string send_to, string message, string phone)
{
    var email = HttpContext.Session.GetString("email");
    MySqlDataReader reader;           
    try
    {
        cmdMySQL.Connection = conMySQL;
        conMySQL.Open();
        cmdMySQL.CommandText = "SELECT * FROM tbl_mensagens WHERE enviado = '" + 0 + "' AND email_usuario = '" + email + "' ";
        reader = cmdMySQL.ExecuteReader();       
        while (reader.Read())
        {
            var codmsgx ="";
            phone = "";
            message = "";        
            codmsgx = reader[0].ToString();
            phone = reader[4].ToString();
            message = reader[5].ToString();
            EnviarMensagem(send_to, message, phone, email, codmsgx);
            AtualizarBd(send_to, message, phone, email, codmsgx);
        }
        reader.Close();           
        return View();
    }
    catch (Exception ex) { Debug.WriteLine(ex); return View(); }
    finally
    {
        conMySQL.Close();
    }
}

You're only getting one row because you're calling reader.Read() . Each time you call Read(), the reader advances to the next row and returns true; or, when the reader advances past the last row, it returns false.

Assume that you have a view model:

public class MensagensViewModel
{
    public string Codmsgx { get; set; }
    public string Phone { get; set; }
    public string Message { get; set; }
}

To get the List<MensagensViewModel> data from tbl_mensagens table, you need to manually save the accessed data into mensagens shown as below code:

try
    {
        cmdMySQL.Connection = conMySQL;             
        cmdMySQL.CommandText = "SELECT * FROM tbl_mensagens WHERE enviado = '" + 0 + "' AND email_usuario = '" + email + "' ";
        conMySQL.Open();
        reader = cmdMySQL.ExecuteReader();

        List<MensagensViewModel> mensagens = new List<MensagensViewModel>();//To save all retrieved data
        while (reader.Read())
        {
            var mensagen = new MensagensViewModel()
                {
                    Codmsgx = reader[0].ToString(),
                    Phone = reader[4].ToString(),
                    Message = reader[5].ToString()
                };

            mensagens.Add(mensagen);
            //other logic                 

        }
        reader.Close();
        return View();
    }
    catch (Exception ex) { Debug.WriteLine(ex); return View(); }
    finally
    {
        conMySQL.Close();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM