0

I was trying to upload and then see an image, saving it in a MS Access database.

I configure the column as "Long text" in Access for saving the bytes image.

This is the code that saves my image:

MemoryStream ms = new MemoryStream();
pb_Imagen.Image.Save(ms, ImageFormat.Jpeg);
byte[] aByte = ms.ToArray();
        
OleDbConnection MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data source = d:\\Archivos\\Descargas\\FastCare(1)\\Base de Datos\\Usuarios.accdb");
string comandSQL = "INSERT INTO Trabajadores (Nombre, Telefono, Rut, Email, Edad, Sexo, Estudios, Descripcion, Experiencia, Niños, Adultos, Imagen) VALUES ('"+_Nombre+"' , '"+_Telefono+"' , '"+_Rut+"', '"+_Email+"', '"+_Edad+"', '"+_Sexo+"', '"+_Estudios+"', '"+_Descripcion+"', '"+_Experiencia+"', '"+_Ninos+"', '"+_Adultos+"', @imagen)";
        
try
{
    MyConnection.Open();
}
catch(Exception ex)
{
    return "No se puede conectar con la Base de Datos"+ex.Message;
}

OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand CommandQuery = new OleDbCommand(comandSQL, MyConnection);
CommandQuery.Parameters.AddWithValue("@imagen", aByte);

try
{
    adapter.InsertCommand = CommandQuery;
    adapter.InsertCommand.ExecuteNonQuery();
    return "Tu perfil como trabajador/a se registró correctamente";     
}
catch(Exception ex)
{
    return "No se pudo registrar, intente nuevamente"+ex.Message;   
}

This is the code to retrieve the image:

OleDbCommand consulta = new OleDbCommand("SELECT * FROM Trabajadores WHERE Nombre='"+cmb_Nombre.Text+"'");
            AbrirConexion();
            consulta.Connection = conexion;

OleDbDataReader leer = consulta.ExecuteReader();
            
if (leer.HasRows)
{
    leer.Read();
    MemoryStream ms = new MemoryStream((byte[])leer["Imagen"]);
    Bitmap bm = new Bitmap(ms);
    pb_Imagen.Image = bm;
}   
else
{
    MessageBox.Show("No se encontraron registros");
}

When I upload an image, I get no error message, but when I want to see the picture associated with "Nombre", I get this error:

System.InvalidCastException: Cannot cast object of type 'System.String' to type 'System.Byte []'.

Dharman
  • 30,962
  • 25
  • 85
  • 135

0 Answers0