Search code examples
c#mysqlmysqldatareader

Unable to Get value from MySQL and print to TextBox


So this method is supposed to get the ipaddress of the logged in user from a MySQL Database and print it to a textbox. However, I cant seem to get it right as the program just closes after I execute this method.

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

If anyone could point out where I went wrong, I greatly appreciate your help!

Edit: After using try and catch I get this:

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

Solution

  • Quick Fix:

    You are executing the command two times, using ExecuteReader that's why you are getting such exception. If you execute the code like this means your code will works fine:

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

    Smart Fix:

    Here you are fetching a single value from the database in such situations you need not to use reader at all. you can simply access those value by using ExecuteScalar() method, which will give you the required object. if so You can use the following code:

    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";
        }
    }
    

    Hope that you wont forget to add MySql.Data.MySqlClient; to the using section