Search code examples
c#mysqlif-statementdecimaldatareader

Getting GetDecimal to work


MySqlConnection con = new MySqlConnection("host=*;user=*;password=*;database=*;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM members WHERE username = '" + textBox2.Text + "' AND password = '" + textBox3.Text + "';");
cmd.Connection = con;
DataTable dt = new DataTable();
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();

if (reader.Read() != false)
{
    if (reader.IsDBNull(0) == true)
    {
        cmd.Connection.Close();
        reader.Dispose();
        cmd.Dispose();
        MessageBox.Show("Oops!There was a problem!");
    }
    else
    {
        cmd.Connection.Close();
        reader.Dispose();
        cmd.Dispose();
        this.Hide();
        Main main = new Main();
        main.Show();
        MySqlCommand cmmd = new MySqlCommand("SELECT Pain FROM members WHERE username='" + textBox2.Text + "';");
        cmmd.Connection = con;
        con.Open();
        MySqlDataReader read = cmmd.ExecuteReader();
        if (read.Read())
        {
            if (read.GetDecimal(0) == 1)
            {
                MessageBox.Show("NO");
                cmmd.Connection.Close();
                read.Dispose();
                cmmd.Dispose();
            }
            else
            {
                MessageBox.Show("YES");
                cmmd.Connection.Close();
                read.Dispose();
                cmmd.Dispose();
            }
    }
}
else
{
    MessageBox.Show("You Login Information is incorrect!");
}

I want the C# to read the PAIN column and if it's equal to 0 to show the message NO and if it's equal to 1 to show the message YES.The pain Collumn is an INT type and is the 8th column


Solution

  • Try as below.

    using (var con = new MySqlConnection("host=*;user=*;password=*;database=*;"))
    using (var cmd = con.CreateCommand())
    {
        cmd.CommandText = "SELECT username, Pain FROM members WHERE username = @UserName AND password = @Password";
        cmd.Parameters.AddWithValue("@UserName", textBox2.Text);
        cmd.Parameters.AddWithValue("@Password", textBox3.Text);
    
        con.Open();
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                var username = reader.GetString(0);
    
                if (!reader.IsDBNull(1))
                {
                    var pain = reader.GetInt32(1);
                    if (pain == 1)
                    {
                        MessageBox.Show("NO");
                    }
                    else
                    {
                        MessageBox.Show("YES");
                    }
                }
            }
            else
            {
                MessageBox.Show("You Login Information is incorrect!");
            }
    
        }
    
    }