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

时间:2016-12-16 03:48:02

标签: c# mysql mysqldatareader

所以这个方法应该从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和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

3 个答案:

答案 0 :(得分: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;添加到使用部分

答案 1 :(得分:0)

您正在通过调用ExecuteReader()执行阅读器两次,这里为什么需要Reader,如果您只需要数据库中的一个值。使用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

}

答案 2 :(得分:0)

问题:

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

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