gpt4 book ai didi

mysql - 使用asp.net core查询Mysql数据库

转载 作者:行者123 更新时间:2023-11-29 15:44:03 27 4
gpt4 key购买 nike

我需要查询数据库。该查询工作正常,但我需要循环读取表中的所有数据。我不知道如何在此查询中添加“do”或“while”

[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();
}
}

最佳答案

您只得到一行,因为您正在调用 reader.Read() 。每次调用 Read() 时,读取器都会前进到下一行并返回 true;或者,当读取器前进到最后一行时,它返回 false。

假设您有一个 View 模型:

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

获取List<MensagensViewModel>数据来自tbl_mensagens表中,需要手动将访问的数据保存到mensagens中代码如下所示:

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();
}

关于mysql - 使用asp.net core查询Mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268106/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com