FireDAC 下的 Sqlite [5] - 数据的插入、更新、删除

前端之家收集整理的这篇文章主要介绍了FireDAC 下的 Sqlite [5] - 数据的插入、更新、删除前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
先在空白窗体上添加: TFDConnection、TFDPhyssqliteDriverLink、TFDGUIxWaitCursor、TFDQuery、TDataSource、TDBGrid(并在设计时关联好).

你也可以复制下面文本框中的内容,然后直接往窗体上贴,以快速完成以上的添加过程:


object DBGrid1: TDBGrid
Left = 16
Top = 88
Width = 361
Height = 329
DataSource = DataSource1
TabOrder = 0
TitleFont.Charset = DEFAULT_CHARSET
TitleFont.Color = clWindowText
TitleFont.Height = -11
TitleFont.Name = 'Tahoma'
TitleFont.Style = []
end
object FDConnection1: TFDConnection
Left = 34
Top = 24
end
object FDPhyssqliteDriverLink1: TFDPhyssqliteDriverLink
Left = 143
Top = 24
end
object FDGUIxWaitCursor1: TFDGUIxWaitCursor
Provider = 'Forms'
Left = 260
Top = 24
end
object FDQuery1: TFDQuery
Connection = FDConnection1
Left = 344
Top = 24
end
object DataSource1: TDataSource
DataSet = FDQuery1
Left = 420
Top = 24
end
object Button1: TButton
Left = 400
Top = 88
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 1
OnClick = Button1Click
end
object Button2: TButton
Left = 400
Top = 136
Width = 75
Height = 25
Caption = 'Button2'
TabOrder = 2
OnClick = Button2Click
end
object Button3: TButton
Left = 400
Top = 192
Width = 75
Height = 25
Caption = 'Button3'
TabOrder = 3
OnClick = Button3Click
end
object Button4: TButton
Left = 400
Top = 240
Width = 75
Height = 25
Caption = 'Button4'
TabOrder = 4
OnClick = Button4Click
end
end



代码:
{建立}
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;
原文链接:https://www.f2er.com/sqlite/199555.html

猜你在找的Sqlite相关文章