Firedac是Delphi开发跨平台的数据库应用程序的通用数据访问组件,同样适用于C++ Builder和FreePascal。这里是Firedac操作Sqlite的学习笔记。文中代码在Delphi 11中编译通过。
先将“FireDAC 和 Sqlite 一 :基本控件和设置”一篇中提到的常用控件加入Form,并做好关联。
再按照“FireDAC 和 Sqlite 二:创建数据库和表”一篇中介绍建立数据库和表。
例子一:把内存流写入数据库后,再读出到另一个内存流,进行比对
procedure TForm1.Button1Click(Sender: TObject); var stm1,stm2:TmemoryStream; Buf:TBytes; const Data: Array[0..2] of byte =(200,201,202); begin //初始化 SetLength(Buf,3); stm1:=TmemoryStream.Create; stm2:=TmemoryStream.Create; stm1.Write(Data,3);//把Data数据写入stm1 //插入 FDQuery1.SQL.Clear; FDQuery1.SQL.Text :='INSERT INTO MyTable(Name, Age,Picture) VALUES(:name, :age, :Picture)'; FDQuery1.ParamByName('Name').AsString := 'Tom'; FDQuery1.ParamByName('age').AsByte := 12; FDQuery1.ParamByName('Picture').LoadFromStream(stm1,ftBlob ,-1);//数据从stm1写入数据库 FDQuery1.ExecSQL; FDQuery1.Open('SELECT * FROM MyTable');//如果是修改打开的表,改完要重新打开 //读取 FDQuery1.SQL.Clear; FDQuery1.SQL.Text := 'SELECT * FROM MyTable WHERE Age = :x'; FDQuery1.ParamByName('x').AsInteger := 12; FDQuery1.Open(); TBlobField(FDQuery1.FieldByName('Picture')).SaveToStream(stm2);//数据读出到stm2 //TBlobField(FDQuery1.FindField('Picture')).SaveToStream(stm2);//与上同 stm2.position:=0;//重新定位 stm2.Read(Buf,3);//把stm1数据写入Buf //显示比对 Memo1.Text:=FDQuery1.FieldByName('Name').AsString; //Memo1.Text:=FDQuery1.FindField('Name').AsString;//与上同 Memo1.Lines.Add(inttostr(Buf[0])); Memo1.Lines.Add(inttostr(Buf[1])); Memo1.Lines.Add(inttostr(Buf[2])); //释放内存流 stm1.Free; stm2.Free; end;
例子二:把内存流写入数据库后,再以数组的形式读出,进行比对
procedure TForm1.Button20Click(Sender: TObject); var stm1:TmemoryStream; Buf:TBytes; const Data: Array[0..2] of byte =(200,201,202); begin //初始化 SetLength(Buf,3); stm1:=TmemoryStream.Create; stm1.Write(Data,3);//把Data数据写入stm1 //插入 FDQuery1.SQL.Clear; FDQuery1.SQL.Text :='INSERT INTO MyTable(Name, Age,Picture) VALUES(:name, :age, :Picture)'; FDQuery1.ParamByName('Name').AsString := 'Tom'; FDQuery1.ParamByName('age').AsByte := 12; FDQuery1.ParamByName('Picture').LoadFromStream(stm1,ftBlob ,-1);//数据从stm1写入 FDQuery1.ExecSQL; FDQuery1.Open('SELECT * FROM MyTable');//如果是修改打开的表,改完要重新打开 //读取 FDQuery1.SQL.Clear; FDQuery1.SQL.Text := 'SELECT * FROM MyTable WHERE Age = :x'; FDQuery1.ParamByName('x').AsInteger := 12; FDQuery1.Open(); Buf:=FDQuery1.FindField('Picture').AsBytes; //显示比对 Memo1.Text:=FDQuery1.FindField('Name').AsString; Memo1.Lines.Add(inttostr(Buf[0])); Memo1.Lines.Add(inttostr(Buf[1])); Memo1.Lines.Add(inttostr(Buf[2])); //释放内存流 stm1.Free; end;