FireDAC 下的 Sqlite [5] - 數據的插入、更新、刪除



先在空白窗體上添加: TFDConnection、TFDPhysSQLiteDriverLink、TFDGUIxWaitCursor、TFDQuery、TDataSource、TDBGrid(並在設計時關聯好).

你也可以復制下面文本框中的內容, 然后直接往窗體上貼, 以快速完成以上的添加過程:


代碼:
{建立}
procedure TForm1.FormCreate(Sender: TObject);
const
  dbPath = 'C:\Temp\SQLiteTest.sdb';
  strTable = 'CREATE TABLE MyTable(Id integer PRIMARY KEY AUTOINCREMENT, Name string(10), Age byte)'; //Id, Name, Age 三個字段
                                                                                                      //integer PRIMARY KEY AUTOINCREMENT: 自增字段
begin
  if FileExists(dbPath) then DeleteFile(dbPath);

  FDConnection1.ConnectionString := 'DriverID=SQLite; Database=' + dbPath;
  FDConnection1.ExecSQL(strTable);

  FDQuery1.Open('SELECT * FROM MyTable');
end;

{插入}
procedure TForm1.Button1Click(Sender: TObject);
const
  strInsert = 'INSERT INTO MyTable(Name, Age) VALUES(:name, :age)'; //:name, :age 的方式(后面還要以數組的方式給出相應的值), 這比字符串的 Format 函數還要方便.
begin
  FDConnection1.ExecSQL(strInsert, ['AAA', 11]);
  FDConnection1.ExecSQL(strInsert, ['BBB', 22]);
  FDConnection1.ExecSQL(strInsert, ['CCC', 33]);
  FDConnection1.ExecSQL(strInsert, ['DDD', 44]);
  FDConnection1.ExecSQL(strInsert, ['EEE', 55]);
  FDQuery1.Refresh;
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 Age FROM MyTable WHERE Name = :x', ['BBB']);
  ShowMessage(V);
end;

//:
select * from test where name = 'ABCDE' COLLATE NOCASE;
create table test (id Integer,name Text COLLATE NOCASE );



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM