使用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));
            }                     
        }

解决方法

我在您的代码中看到很多问题:

  1. 它是西班牙语-应该避免,特别是如果您需要来自非西班牙人的帮助
  2. 您永远不会丢弃IDisposable对象(例如MySqlConnection)
  3. 您在try catch中有一个无用的try catch,而在内部catch中,您没有处理异常
  4. 您的查询将参数作为字符串附加,而不是将参数作为sqlparameters传递,这使您的代码容易受到sql注入的攻击
  5. 您正在执行字符串的Convert.ToString
  6. 在查询中,分组之前缺少空格,这将破坏语法
,

根据我的研究,您的问题是由于查询结果为空。

我建议您可以在填充文本框之前判断查询结果。

您可以尝试以下代码:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...