Firedac是Delphi开发跨平台的数据库应用程序的通用数据访问组件,同样适用于C++ Builder和FreePascal。这里是Firedac操作Sqlite的学习笔记。文中代码在Delphi 11中编译通过。
先将“FireDAC 和 Sqlite 一:基本控件和设置”一篇中提到的常用控件加入Form,并做好关联。
一. 数据的插入
procedure TForm1.Button1Click(Sender: TObject); const Table:string = 'CREATE TABLE MyTable(Id Integer PRIMARY KEY AUTOINCREMENT, Name String(10), Age Byte)'; //Id, Name, Age 三个字段 //Integer PRIMARY KEY AUTOINCREMENT: 自增字段 Insert:string = 'INSERT INTO MyTable(Name, Age) VALUES(:name, :age)'; begin //先创建表 FDConnection1.ExecSQL(Table); //方法一 FDQuery1.Open('SELECT * FROM MyTable'); FDConnection1.ExecSQL(Insert, ['AAA', 11]); FDConnection1.ExecSQL(Insert, ['BBB', 22]); FDConnection1.ExecSQL(Insert, ['CCC', 33]); FDQuery1.Refresh;//如果是修改打开的表,改完只要刷新即可 //方法二 FDQuery1.SQL.Clear; FDQuery1.SQL.Text :=Insert; FDQuery1.ParamByName('Name').AsString := 'FFF'; FDQuery1.ParamByName('age').AsByte := 66; FDQuery1.ExecSQL; FDQuery1.Open('SELECT * FROM MyTable');//如果是修改打开的表,改完要重新打开 end;
二. 数据的更新
procedure TForm1.Button2Click(Sender: TObject); begin FDConnection1.ExecSQL('UPDATE MyTable SET Age=:a WHERE Name=:n', [Random(100), 'AAA']); FDQuery1.Refresh; end;
三. 数据的删除
procedure TForm1.Button3Click(Sender: TObject); begin FDConnection1.ExecSQL('DELETE FROM MyTable WHERE Age>33'); FDQuery1.Refresh; end;
四. 数据的查询
procedure TForm1.Button4Click(Sender: TObject); var V: Variant; begin //方法一: //通过年龄查名字 V := FDConnection1.ExecSQLScalar('SELECT Name FROM MyTable WHERE Age = :x', ['22']); ShowMessage(V); //通过名字查年龄 V := FDConnection1.ExecSQLScalar('SELECT Age FROM MyTable WHERE Name = :x', ['FFF']); ShowMessage(V); //方法二: //通过年龄查名字 FDQuery1.SQL.Clear; FDQuery1.SQL.Text := 'SELECT * FROM MyTable WHERE Age = :x'; FDQuery1.ParamByName('x').AsInteger := 22; FDQuery1.Open(); Memo1.Text:=FDQuery1.FieldByName('Name').AsString; end;
五. 获取Insert的自增ID
procedure TForm1.Button11Click(Sender: TObject); begin //方法一: showmessage( FDConnection1.GetLastAutoGenValue('MyTable') ); //方法二: FDQuery1.Open('SELECT last_insert_rowid()'); showmessage(FDQuery1.Fields[0].Value); FDQuery1.Open('SELECT * FROM MyTable');//如果是查询打开的表,查完后要重新打开 end;