【问题标题】:Unable to Get value from MySQL and print to TextBox无法从 MySQL 获取价值并打印到 TextBox
【发布时间】:2016-12-16 03:48:02
【问题描述】:

所以这个方法应该从 MySQL 数据库中获取登录用户的 ipaddress 并将其打印到文本框。但是,我似乎无法正确处理,因为在我执行此方法后程序刚刚关闭。

    public void readIPAddress()
    {
        string username = GlobalData._sharedUserName;
        String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
        conn = new MySql.Data.MySqlClient.MySqlConnection(connString);

        conn.Open();
        queryStr = "";
        queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=?username";
        cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
        cmd.Parameters.AddWithValue("?username", username);
        cmd.ExecuteReader();

        while (cmd.ExecuteReader().Read())
        {
            textBoxIPAddress.Text = reader["ipaddress"].ToString();
        }

        conn.Close();
    }

如果有人能指出我哪里出错了,我非常感谢你的帮助!

编辑:使用 try and catch 后,我得到了这个:

MySql.Data.MySqlClient.MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first.
   at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
   at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
   at MySql.Data.MySqlClient.MySqlCommand.CheckState()
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
   at ConnectToDataBase.Form2.readIPAddress() in C:\Users\ee\Dropbox\ConnectToDataBase\ConnectToDataBase\Form2.cs:line 95

【问题讨论】:

  • 如果有异常,使用try catch跟踪异常,为什么要执行两次使用ExecuteReader的命令?
  • 建议:checkout MySql.Data.MySqlClient.MySqlHelper class。您可能会发现它更容易使用。
  • 编辑评论:此代码不会编译,因为 reader 未定义
  • 阅读器在方法之外定义为
  • reader 在方法之外定义为 MySql.Data.MySqlClient.MySqlDataReader reader;

标签: c# mysql mysqldatareader


【解决方案1】:

快速修复:

您使用ExecuteReader 执行了两次命令,这就是您收到此类异常的原因。如果您像这样执行代码,则意味着您的代码可以正常工作:

string queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=@username";
using (MySqlConnection conn = new MySqlConnection(connString))
{
    conn.Open();
    using (MySqlCommand cmd = new MySqlCommand(queryStr, conn))
    {
        cmd.Parameters.AddWithValue("@username", username);
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            textBoxIPAddress.Text = reader["ipaddress"].ToString();
        }
    }
}

智能修复:

在这里,您从数据库中获取单个值,在这种情况下您根本不需要使用阅读器。您可以使用ExecuteScalar() 方法简单地访问这些值,这将为您提供所需的对象。如果是这样您可以使用以下代码:

using(MySqlConnection conn = new MySqlConnection(connString))
{
    using(MySqlCommand cmd= new MySqlCommand(query, conn))
    {
        cmd.Parameters.Add("@username", username);
        conn.Open();
        object ipAddress= cmd.ExecuteScalar();
        if (ipAddress!= null) 
           textBoxIPAddress.Text = ipAddress.ToString();
        else
           textBoxIPAddress.Text = "No data found";
    }
}

希望你不会忘记在使用部分添加MySql.Data.MySqlClient;

【讨论】:

    【解决方案2】:

    您通过调用ExecuteReader() 执行了两次阅读器,如果您只需要数据库中的一个值,为什么在这里需要阅读器。使用ExecuteScalar,它将从结果中返回第一条记录的第一个值。示例代码:

    try
    {
        string query = "SELECT ipaddress FROM webappdemo.userregistration WHERE username = @username";
        string connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
        using(MySqlConnection connection = new MySqlConnection(connString))
        {
            using(MySqlCommand command = new MySqlCommand(query, connection))
            {
                command.Parameters.Add("@username", username);
    
                connection.Open();
                object ip= command.ExecuteScalar();
                if (ip != null) {
                  textBoxIPAddress.Text = ip.ToString();
                }
            }
        }
    }
    catch(MySqlException ex)
    {
        // do something with the exception
    
    }
    

    【讨论】:

      【解决方案3】:

      问题:

          cmd.ExecuteReader(); //Executing reader and not assigning to anything
      
          while (cmd.ExecuteReader().Read()) //Executing reader again and not assigning to anything again
          {
              //There is nothing assigned to reader.
              textBoxIPAddress.Text = reader["ipaddress"].ToString(); 
          }
      

      快速解决方案:

          //assuming reader is defined
          reader = cmd.ExecuteReader();
      
          while (reader.Read()) //read from the reader
          {
              textBoxIPAddress.Text = reader["ipaddress"].ToString(); 
          }
      

      使用MySql.Data.MySqlClient.MySqlHelper 的替代解决方案:

      try {
          object ip = MySqlHelper.ExecuteScalar(connString, query, new MySqlParameter[] {
                                          new MySqlParameter("?username", username) 
                                      }));
          if (ip != null) {
              textBoxIPAddress.Text = ip.ToString();
          }
      } catch (Exception ex) {
          // do something with the exceptio
      }
      

      如果你坚持使用阅读器:

      //assuming reader is defined
      reader = MySqlHelper.ExecuteReader(connString, query, new MySqlParameter[] {
                                      new MySqlParameter("?username", username) 
                                  }));
      while (reader.Read()) //read from the reader
      {
          textBoxIPAddress.Text = reader["ipaddress"].ToString(); 
      }
      

      注意:上面的代码只是在这里输入的,可能包含语法错误。以此为准则。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-21
        • 2015-09-08
        • 1970-01-01
        相关资源
        最近更新 更多