Lazarus中對mysql資料庫Blob型別進行讀寫例子

禁卫军發表於2024-09-27

一、讀一個圖片到資料庫

var

inimage1:TImage;
TPStream:TMemoryStream;

inimage1 := TImage.Create(nil);
//讀取圖片
TPStream := TMemoryStream.Create;
Image1.Picture.SaveToStreamWithFileExt(TPStream, 'jpg');//生成jpeg圖片
inimage1.Free;
TPStream.Position := 0;
sqlst := format('UPDATE userinfo SET tp=:tp WHERE id=%d',[userid]);
Form1.SQLQuery1.Close;
Form1.SQLQuery1.SQL.Text := sqlst;
Form1.SQLQuery1.ParamByName('tp').SetBlobData(TPStream.Memory,TPStream.Size);
Form1.SQLQuery1.ExecSQL;
TPStream.Free;

二、從資料庫中得到圖片資料

TPStream:=TMemoryStream.Create;
TPStream.Write(Form1.SQLQuery1.FieldByName('tp').AsBytes,Length(Form1.SQLQuery1.FieldByName('tp').AsBytes));
TPStream.Position:=0;
Image1.Picture.LoadFromStream(TPStream);
TPStream.Free;

三、寫一個浮點資料到資料庫

var

psin:PSingle;

fcLen:integer;

psin:= GetMem(fcLen * SizeOf(single));

//寫浮點資料值

sqlst := format(
'UPDATE userinfo SET tzm=:tzm WHERE id=%d',
[userid]);
Form1.SQLQuery1.Close;
Form1.SQLQuery1.SQL.Text := sqlst;
Form1.SQLQuery1.ParamByName('tzm').SetBlobData(psin, fcLen * SizeOf(single));
Form1.SQLQuery1.ExecSQL;
FreeMemAndNil(psin);

四、從資料庫中讀取浮點數

TZMStream:=TMemoryStream.Create;
lenp:=Length(Form1.SQLQuery1.FieldByName('tzm').AsBytes);
psin:=GetMem(lenp);
Move(Form1.SQLQuery1.FieldByName('tzm').AsBytes[0],psin^,lenp);
FreeMemAndNil(psin);

相關文章