-3

I am developing a program in C # with .NET and MySQL databases. I need the user image to be visible once the user is logged in, for which I have a LONGBLOB type column called 'Image'. The login process was good, but the following error occurred

Connection must be valid and open.

I'm using the following code to select from the database:

MySqlCommand command1 = new MySqlCommand("select `user Image` from `userdb` where `username` = @img", con);
        
        command1.Parameters.Add("@img", MySqlDbType.Blob);
        
        command1.Parameters["@img"].Value = Admin;

        byte[] img = (byte[])command1.ExecuteScalar();

        if (img == null)
        {
            pic_profilePic.Image = null;
        }
        else
        {
            var DATA = (byte[])command1.ExecuteScalar();
            var stream = new MemoryStream(DATA);
            pic_profilePic.Image = Image.FromStream(stream);
        }

Despite changing the column type into binary and varbinary, I still got the same error.

Does anyone know what I'm doing wrong here?

MrTux
  • 32,350
  • 30
  • 109
  • 146
  • 2
    Well, according to the exception, the connection you are passing as the second parameter to `MySqlCommand` is not open. Did you call the `Open()` method on it before you passed it to `MySqlCommand`? Unfortunately, you didn't post the relevant part of the code in your question - where is the declaration of the `con` variable? – NightOwl888 May 15 '22 at 09:14

1 Answers1

0
string cs = @"server=localhost;userid=dbuser;password=s$cret;database=testdb";

var con = new MySqlConnection(cs);
con.Open(); //did you open after you initialize the connection?

Please check your code to open your connection

Also remember to close it after you are done

con.Close();
Allanckw
  • 641
  • 1
  • 6
  • 17