c# - 使用 MySqlDataReader C#
问题描述
我正在尝试使用 mysqldatareader 在 C# Visual Studio 中填充一些文本框。我已经创建了连接字符串并创建了 MySqlDataReader 命令。
但是当我单击按钮进行操作时,它会显示一个消息框,上面写着:“在调用 Read() 之前访问字段的尝试无效”
这是我的代码:
private void btnBuscar_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conexao = new MySqlConnection("server=localip; database=localdb; Uid=user; pwd=pass;");
conexao.Open();
MySqlCommand comando = new MySqlCommand();
comando.CommandText = "select p.id, s.sku_id, p.commercial_description, pri.price, max(pri.start) as alterado_em from plu p " +
"inner join sku s on p.plu_key = s.plu_key inner join pricing pri on pri.plu_key = p.plu_key " +
"where p.id = " + txtCodbusca.Text + " group by pri.plu_key desc";
comando.CommandType = CommandType.Text;
comando.Connection = conexao;
MySqlDataReader DR;
DR = comando.ExecuteReader();
DR.Read();
txtCodinterno.Text = Convert.ToString(DR.GetDecimal(0));
txtGtin.Text = Convert.ToString(DR.GetChar(1));
txtDescricao.Text = (DR.GetString(2));
txtPreco.Text = Convert.ToString(DR.GetDecimal(3));
conexao.Close();
HabBotoes();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("{0}", ex.Message));
}
}
解决方案
根据我的研究,您的问题是由于查询结果为空。
我建议你可以在填充文本框之前判断查询结果。
您可以尝试以下代码:
DR = comando.ExecuteReader();
if (DR.HasRows)
{
DR.Read();
txtCodinterno.Text = Convert.ToString(DR.GetDecimal(0));
txtGtin.Text = Convert.ToString(DR.GetChar(1));
txtDescricao.Text = (DR.GetString(2));
txtPreco.Text = Convert.ToString(DR.GetDecimal(3));
}
else
{
MessageBox.Show("The query result of p.id=" + txtCodbusca.Text + " is empty");
}
conexao.Close();
推荐阅读
- c++ - 你为什么要 =delete 隐式删除的默认构造函数,这有什么意义?
- excel - 如何将多个条件应用于.Find?
- c# - 访问 DbPropertyValues 复杂类型
- reactjs - 在 reactjs 中结合 SimpleBar + Drawer (MaterialUI)
- matlab - 我试图从概率分布中生成两个值,但一个分布没有正确生成值
- javascript - 隐藏错误文本,直到单击框/按钮
- scala.js - 如果使用 scala 函数,scalajs removeEventListener 不起作用
- python - 在 Python 中,如何在循环中对原始类型进行操作?
- postgresql - 列参考 id 不明确 postgres
- pandas - 取熊猫中多个列的平均值