无法从 MySQL 获取值并打印到 TextBox

Unable to Get value from MySQL and print to TextBox

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

    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

你通过调用 ExecuteReader() 执行了两次 reader,如果你只需要数据库中的一个值,为什么你需要 Reader 这里。使用 ExecuteScalar 将 return 结果中第一条记录的第一个值。示例代码:

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

}

快速修复:

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

智能修复:

在这种情况下,您根本不需要使用 reader,这里是从数据库中获取单个值。您可以使用 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; 添加到使用部分

问题:

    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
}

如果你坚持使用reader:

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

注意:以上代码只是在这里输入,可能存在语法错误。以此为指导。