How to insert / retrieve image in MySQL database

6

Would you like to know in a clear and simple way how to insert / retrieve an image in the MySQL database?

I'm using FireDac to connect to the MySQL database.

I have a JPEG image and want to save it to a MySQL database and be able to restore it when needed. From what I could see it's something like blob data type, but I do not know the right way to do it.

    
asked by anonymous 17.01.2016 / 16:05

1 answer

5

After a connection made with FireDac , you can use one of your own components to execute the SQLs commands.

The component is on the same tab as FireDacconnection , it is FDQuery .

Saving the image in the Database:

procedure frmTeste.btnIncluirFotoClick(Sender: TObject);
var
  vArquivo: TFileStream;
begin
  vArquivo := TFileStream.Create('d:.bmp', fmOpenRead or fmShareDenyWrite);
  FDQuery1.Close;
  FDQuery1.SQL.Clear;
  //Pode ser feito Insert ou Update
  FDQuery1.SQL.Add('INSERT INTO tbl_usuario (FOTO) VALUES(:FOTOCARREGADA)');
  FDQuery1.Params[0].DataType := ftBlob;
  FDQuery1.ParamByName('FOTOCARREGADA').AsStream := vArquivo;
  FDQuery1.ExecSQL;
  FDQuery1.Close;
end;

Reading the database image:

procedure frmTeste.btnCarregarFotoClick(Sender: TObject);
var
  vFoto   : TStream;
  vImagem : TBitmap;
begin     
  FDQuery1.Close;
  FDQuery1.SQL.Add('SELECT * FROM tbl_usuario WHERE id_usuario = 6');
  FDQuery1.Open;

  //Lendo a imagem do campo BLOB para a Memória
  vFoto := FDQuery1.CreateBlobStream(FDQuery1.FieldByName('FOTO'), bmRead);

  //Criando a instância de TBitmap (pode ser JPG tb)
  vImagem := TBitmap.Create;

  //Carregando a imagem a partir do stream TStream
  vImagem.LoadFromStream(vFoto);

  //Exibindo a Imagem
  Image1.Picture.Assign(vImagem);
  //Image1.Bitmap.LoadFromStream(vFoto); //Caso esteja usando FMX ao invés de VCL
end;

To be successful at recording and reading data, the choice of the Blob field should be taken into account!

Here is a question that I asked right here with good answers about the field BLOB

    
17.01.2016 / 20:32