Recent

Author Topic: Why can my TQuery perform read operations but cannot successfully execute insert  (Read 1605 times)

akjarjash

  • Newbie
  • Posts: 4
project1.lpr
Code: Pascal  [Select][+][-]
  1. program project1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.       {$IFDEF UNIX}
  7.       cthreads,
  8.       {$ENDIF}
  9.       {$IFDEF HASAMIGA}
  10.       athreads,
  11.       {$ENDIF}
  12.       Interfaces, // this includes the LCL widgetset
  13.       Forms, unit1
  14.       { you can add units after this };
  15.  
  16. {$R *.res}
  17.  
  18. begin
  19.       RequireDerivedFormResource:=True;
  20.       Application.Scaled:=True;
  21.       Application.Initialize;
  22.                         Application.CreateForm(TForm1, Form1);
  23.       Application.Run;
  24. end.
  25.  


Unit1.lfm
Code: Pascal  [Select][+][-]
  1. object Form1: TForm1
  2.   Left = 452
  3.   Height = 227
  4.   Top = 151
  5.   Width = 608
  6.   Caption = 'Form1'
  7.   ClientHeight = 227
  8.   ClientWidth = 608
  9.   OnCreate = FormCreate
  10.   object DBGrid1: TDBGrid
  11.     Left = 16
  12.     Height = 208
  13.     Top = 8
  14.     Width = 400
  15.     Color = clWindow
  16.     Columns = <    
  17.       item
  18.         Title.Caption = '编号'
  19.         FieldName = 'id'
  20.       end    
  21.       item
  22.         Title.Caption = '姓名'
  23.         FieldName = 'name'
  24.       end    
  25.       item
  26.         Title.Caption = '年龄'
  27.         FieldName = 'age'
  28.       end>
  29.     DataSource = DataSource1
  30.     Options = [dgEditing, dgTitles, dgIndicator, dgColumnResize, dgColumnMove, dgColLines, dgRowLines, dgTabs, dgAlwaysShowSelection, dgConfirmDelete, dgCancelOnExit, dgDisplayMemoText]
  31.     TabOrder = 0
  32.   end
  33.   object Label1: TLabel
  34.     Left = 432
  35.     Height = 17
  36.     Top = 15
  37.     Width = 36
  38.     Caption = '姓名:'
  39.   end
  40.   object Label2: TLabel
  41.     Left = 432
  42.     Height = 17
  43.     Top = 50
  44.     Width = 36
  45.     Caption = '年龄:'
  46.   end
  47.   object EditUserName: TEdit
  48.     Left = 486
  49.     Height = 25
  50.     Top = 11
  51.     Width = 98
  52.     TabOrder = 1
  53.   end
  54.   object EditUserAge: TEdit
  55.     Left = 486
  56.     Height = 25
  57.     Top = 46
  58.     Width = 96
  59.     TabOrder = 2
  60.   end
  61.   object Button1: TButton
  62.     Left = 432
  63.     Height = 25
  64.     Top = 88
  65.     Width = 75
  66.     Caption = '新增'
  67.     TabOrder = 3
  68.     OnClick = Button1Click
  69.   end
  70.   object Button2: TButton
  71.     Left = 512
  72.     Height = 25
  73.     Top = 88
  74.     Width = 75
  75.     Caption = '更新'
  76.     TabOrder = 4
  77.   end
  78.   object Button3: TButton
  79.     Left = 432
  80.     Height = 25
  81.     Top = 128
  82.     Width = 75
  83.     Caption = '查询'
  84.     TabOrder = 5
  85.   end
  86.   object Button4: TButton
  87.     Left = 512
  88.     Height = 25
  89.     Top = 128
  90.     Width = 75
  91.     Caption = '编辑'
  92.     TabOrder = 6
  93.   end
  94.   object SQLite3Connection1: TSQLite3Connection
  95.     Connected = True
  96.     LoginPrompt = False
  97.     DatabaseName = 'C:\Users\akjarjash\Desktop\student.db'
  98.     KeepConnection = True
  99.     Transaction = SQLTransaction1
  100.     AlwaysUseBigint = False
  101.     Left = 424
  102.     Top = 168
  103.   end
  104.   object SQLQuery1: TSQLQuery
  105.     IndexName = 'DEFAULT_ORDER'
  106.     MaxIndexesCount = 4
  107.     FieldDefs = <    
  108.       item
  109.         Name = 'id'
  110.         DataType = ftAutoInc
  111.         Precision = -1
  112.       end    
  113.       item
  114.         Name = 'name'
  115.         DataType = ftMemo
  116.         Precision = -1
  117.       end    
  118.       item
  119.         Name = 'age'
  120.         DataType = ftInteger
  121.         Precision = -1
  122.       end>
  123.     Active = True
  124.     Database = SQLite3Connection1
  125.     Transaction = SQLTransaction1
  126.     SQL.Strings = (
  127.       'select'
  128.       '  *'
  129.       'from t_students'
  130.     )
  131.     InsertSQL.Strings = (
  132.       'insert into t_students'
  133.       '  (name, age'
  134.       '  )'
  135.       'values'
  136.       '  (:name, :age'
  137.       '  )'
  138.     )
  139.     UpdateSQL.Strings = (
  140.       'update t_students'
  141.       'set'
  142.       '  name = :name, age = :age'
  143.       'where'
  144.       '   (id = :OLD_id)'
  145.       '  '
  146.     )
  147.     DeleteSQL.Strings = (
  148.       'delete from t_students'
  149.       'where'
  150.       '   (id = :OLD_id)'
  151.       '  '
  152.     )
  153.     RefreshSQL.Strings = (
  154.       'select'
  155.       '  *'
  156.       'from t_students'
  157.       'where'
  158.       '   (id = :id)'
  159.       '  '
  160.     )
  161.     Params = <>
  162.     Macros = <>
  163.     Left = 536
  164.     Top = 168
  165.   end
  166.   object SQLTransaction1: TSQLTransaction
  167.     Active = True
  168.     Database = SQLite3Connection1
  169.     Left = 480
  170.     Top = 168
  171.   end
  172.   object DataSource1: TDataSource
  173.     DataSet = SQLQuery1
  174.     Left = 592
  175.     Top = 168
  176.   end
  177. end
  178.  


Unit1.pas
Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.       Classes, SysUtils, SQLite3Conn, SQLDB, DB, Forms, Controls, Graphics,
  9.                         Dialogs, DBGrids, StdCtrls;
  10.  
  11. type
  12.  
  13.                         { TForm1 }
  14.  
  15.       TForm1 = class(TForm)
  16.                                                 Button1: TButton;
  17.                                                 Button2: TButton;
  18.                                                 Button3: TButton;
  19.                                                 Button4: TButton;
  20.                                                 DataSource1: TDataSource;
  21.                                                 DBGrid1: TDBGrid;
  22.                                                 EditUserName: TEdit;
  23.                                                 EditUserAge: TEdit;
  24.                                                 Label1: TLabel;
  25.                                                 Label2: TLabel;
  26.                                                 SQLite3Connection1: TSQLite3Connection;
  27.                                                 SQLQuery1: TSQLQuery;
  28.                                                 SQLTransaction1: TSQLTransaction;
  29.                                                 procedure Button1Click(Sender: TObject);
  30.       procedure FormCreate(Sender: TObject);
  31.       private
  32.  
  33.       public
  34.  
  35.       end;
  36.  
  37. var
  38.       Form1: TForm1;
  39.  
  40. implementation
  41.  
  42. {$R *.lfm}
  43.  
  44. { TForm1 }
  45.  
  46. procedure TForm1.FormCreate(Sender: TObject);
  47. begin
  48.   // 执行初始化设定工作
  49. end;
  50.  
  51. procedure TForm1.Button1Click(Sender: TObject);
  52. begin
  53.   // 检查用户是否输入相关数据
  54.   if Trim(self.EditUserName.Text) = '' then
  55.   begin
  56.      ShowMessage('学生姓名数据为必填数据!');
  57.      self.EditUserName.Text:='';
  58.      self.EditUserName.SetFocus;
  59.      Exit;
  60.         end;
  61.   if Trim(self.EditUserAge.Text) = '' then
  62.   begin
  63.      ShowMessage('学生姓名数据为必填数据!');
  64.      self.EditUserAge.Text:='';
  65.      self.EditUserAge.SetFocus;
  66.      Exit;
  67.         end;
  68.   // 检查数据库连接对象
  69.   if not self.SQLite3Connection1.Connected then
  70.   begin
  71.     self.SQLite3Connection1.Open;
  72.         end;
  73.         // 检查数据库事务
  74.   if not self.SQLTransaction1.Active then
  75.   begin
  76.      self.SQLTransaction1.StartTransaction;
  77.         end;
  78.   // 进行新增操作前异常处理
  79.   try
  80.         // 检查查询对象的激活状态
  81.     if not self.SQLQuery1.Active then
  82.     begin
  83.        self.SQLQuery1.Active:=True;
  84.         end;
  85.     // 设置数据库新增标记
  86.     self.SQLQuery1.Append;
  87.     // 设置插入语句参数
  88.     self.SQLQuery1.FieldByName('name').AsString:=Trim(self.EditUserName.Text);
  89.     self.SQLQuery1.FieldByName('age').AsInteger:=StrToInt(self.EditUserAge.Text);
  90.     // 执行新增操作
  91.     self.SQLQuery1.Post;
  92.     // 进行事务提交
  93.     self.SQLTransaction1.Commit;
  94.     // 提示用户信息
  95.     ShowMessage('恭喜,新增成功!');
  96.     // 处理编辑框文本
  97.     self.EditUserName.Text:='';
  98.     self.EditUserAge.Text:='';
  99.     // 刷新数据源参数
  100.     self.SQLQuery1.Close;
  101.     self.SQLQuery1.Active:=True;
  102.     self.SQLQuery1.Open;
  103.     self.DataSource1.DataSet.Refresh;
  104.         except
  105.     on E:Exception do
  106.     begin
  107.       self.SQLTransaction1.Rollback;
  108.       ShowMessage('抱歉,系统异常('+E.Message+'),新增失败!');
  109.                 end;
  110.         end;
  111.     end;
  112. end.
  113.  

Zvoni

  • Hero Member
  • *****
  • Posts: 2795
"ApplyUpdates" missing? resp. sqoAutoApplyUpdates not set in TSQLQuery.Options?
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

akjarjash

  • Newbie
  • Posts: 4
I tested it again, and it still doesn't work. Could you provide me with a complete example, similar to the one in the attachment interface, for performing CRUD operations on an SQLite3 database table using buttons?
To facilitate the work, you can use the following prompts through ChatGPT (PS: Although the code generated by ChatGPT in my tests achieves the functionality, I would like to have some template code to speed up the process):


Please provide a complete Lazarus code example that meets the following requirements:
01) Please complete a code example that performs CRUD operations on TDBGrid (Student Basic Information Management System). You can add any controls as needed, and the database should use sqlite3. The database file path is: /Users/akjarjash/Downloads/student.db. The database has a table called t_students with fields: id (auto-increment), name (text), age (integer).
02) The code example files you should output include: `project1.lpr`, `Unit1.lfm`, `Unit1.pas`.
03) Do not omit any file or any content of any file.
04) Note: You need to provide the actual content of the Unit1.lfm file.
05) Note: Avoid referencing the Windows unit in the 'uses' clause of the instance (this is important).
06) Note: In the given Unit1.lfm file, for the Form window, you only need to set the following properties and the events you need:
``` 
Left = 249
Height = 240
Top = 147
Width = 320
Caption = 'Form1'
ClientHeight = 240
ClientWidth = 320
LCLVersion = '3.99.0.0'
```

Handoko

  • Hero Member
  • *****
  • Posts: 5382
  • My goal: build my own game engine using Lazarus
For adding new record you do not have you use TQuery, I usually use ExecuteDirect. You can see my demo:
https://forum.lazarus.freepascal.org/index.php/topic,65185.msg496461.html#msg496461

Zvoni

  • Hero Member
  • *****
  • Posts: 2795
I tested it again, and it still doesn't work. Could you provide me with a complete example, similar to the one in the attachment interface, for performing CRUD operations on an SQLite3 database table using buttons?

I'm the wrong person to ask that.
I don't use "Append", "Post" and whatever else.
I use SQL-Statements. Period
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

akjarjash

  • Newbie
  • Posts: 4
Haha, thank you for your response. With the help of ChatGPT-4 and your advice on "ApplyUpdates," I have resolved the issue and completed a small example. :-)

- SQL
   database:SQLite3  student.db
   
Code: SQL  [Select][+][-]
  1.    CREATE TABLE student_info (
  2.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  3.        name TEXT,
  4.        age INTEGER
  5.    );
  6.    

- project1.lpr
Code: Pascal  [Select][+][-]
  1. program project1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.       {$IFDEF UNIX}
  7.       cthreads,
  8.       {$ENDIF}
  9.       {$IFDEF HASAMIGA}
  10.       athreads,
  11.       {$ENDIF}
  12.       Interfaces, // this includes the LCL widgetset
  13.       Forms, unit1
  14.       { you can add units after this };
  15.  
  16. {$R *.res}
  17.  
  18. begin
  19.       RequireDerivedFormResource:=True;
  20.       Application.Scaled:=True;
  21.       Application.Initialize;
  22.                         Application.CreateForm(TForm1, Form1);
  23.       Application.Run;
  24. end.
  25.  


- Unit1.lfm
Code: Pascal  [Select][+][-]
  1. object Form1: TForm1
  2.   Left = 249
  3.   Height = 297
  4.   Top = 149
  5.   Width = 352
  6.   Caption = '学生基本信息管理系统'
  7.   ClientHeight = 297
  8.   ClientWidth = 352
  9.   LCLVersion = '3.99.0.0'
  10.   OnCreate = FormCreate
  11.   object DBGrid1: TDBGrid
  12.     Left = 8
  13.     Height = 184
  14.     Top = 8
  15.     Width = 331
  16.     Color = clWindow
  17.     Columns = <    
  18.       item
  19.         Title.Caption = '编号'
  20.         FieldName = 'id'
  21.       end    
  22.       item
  23.         Title.Caption = '姓名'
  24.         FieldName = 'name'
  25.       end    
  26.       item
  27.         Title.Caption = '年龄'
  28.         FieldName = 'age'
  29.       end>
  30.     DataSource = DataSource1
  31.     Options = [dgEditing, dgTitles, dgIndicator, dgColumnResize, dgColumnMove, dgColLines, dgRowLines, dgTabs, dgAlwaysShowSelection, dgConfirmDelete, dgCancelOnExit, dgDisplayMemoText]
  32.     TabOrder = 0
  33.     OnCellClick = DBGrid1CellClick
  34.   end
  35.   object Label1: TLabel
  36.     Left = 10
  37.     Height = 16
  38.     Top = 208
  39.     Width = 33
  40.     Caption = '姓名:'
  41.   end
  42.   object EditUserName: TEdit
  43.     Left = 64
  44.     Height = 22
  45.     Top = 205
  46.     Width = 80
  47.     TabOrder = 1
  48.   end
  49.   object Label2: TLabel
  50.     Left = 10
  51.     Height = 16
  52.     Top = 236
  53.     Width = 33
  54.     Caption = '年龄:'
  55.   end
  56.   object EditUserAge: TEdit
  57.     Left = 64
  58.     Height = 22
  59.     Top = 233
  60.     Width = 80
  61.     TabOrder = 2
  62.   end
  63.   object Button1: TButton
  64.     Left = 170
  65.     Height = 25
  66.     Top = 204
  67.     Width = 75
  68.     Caption = '新增'
  69.     TabOrder = 3
  70.     OnClick = Button1Click
  71.   end
  72.   object Button2: TButton
  73.     Left = 264
  74.     Height = 25
  75.     Top = 204
  76.     Width = 75
  77.     Caption = '更新'
  78.     TabOrder = 4
  79.     OnClick = Button2Click
  80.   end
  81.   object Button3: TButton
  82.     Left = 170
  83.     Height = 25
  84.     Top = 232
  85.     Width = 75
  86.     Caption = '查询'
  87.     TabOrder = 5
  88.     OnClick = Button3Click
  89.   end
  90.   object Button4: TButton
  91.     Left = 264
  92.     Height = 25
  93.     Top = 232
  94.     Width = 75
  95.     Caption = '删除'
  96.     TabOrder = 6
  97.     OnClick = Button4Click
  98.   end
  99.   object Button5: TButton
  100.     Left = 10
  101.     Height = 25
  102.     Top = 264
  103.     Width = 326
  104.     Caption = '刷新数据'
  105.     TabOrder = 7
  106.     OnClick = Button5Click
  107.   end
  108.   object SQLite3Connection1: TSQLite3Connection
  109.     Connected = False
  110.     LoginPrompt = False
  111.     DatabaseName = '/Users/akjarjash/Downloads/student.db'
  112.     KeepConnection = True
  113.     Transaction = SQLTransaction1
  114.     AlwaysUseBigint = False
  115.     Left = 32
  116.     Top = 64
  117.   end
  118.   object SQLTransaction1: TSQLTransaction
  119.     Active = False
  120.     Database = SQLite3Connection1
  121.     Left = 112
  122.     Top = 64
  123.   end
  124.   object SQLQuery1: TSQLQuery
  125.     IndexName = 'DEFAULT_ORDER'
  126.     MaxIndexesCount = 4
  127.     FieldDefs = <    
  128.       item
  129.         Name = 'id'
  130.         DataType = ftAutoInc
  131.         Precision = -1
  132.       end    
  133.       item
  134.         Name = 'name'
  135.         DataType = ftMemo
  136.         Precision = -1
  137.       end    
  138.       item
  139.         Name = 'age'
  140.         DataType = ftInteger
  141.         Precision = -1
  142.       end>
  143.     Database = SQLite3Connection1
  144.     Transaction = SQLTransaction1
  145.     SQL.Strings = (
  146.       'SELECT * FROM t_students'
  147.     )
  148.     Params = <>
  149.     Macros = <>
  150.     Left = 32
  151.     Top = 136
  152.   end
  153.   object DataSource1: TDataSource
  154.     DataSet = SQLQuery1
  155.     Left = 112
  156.     Top = 136
  157.   end
  158. end
  159.  


- Unit1.pas
Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils, Forms, Controls, Graphics, Dialogs, DBGrids, StdCtrls,
  9.   SQLite3Conn, SQLDB, DB;
  10.  
  11. type
  12.  
  13.   { TForm1 }
  14.  
  15.   TForm1 = class(TForm)
  16.     Button1: TButton;
  17.     Button2: TButton;
  18.     Button3: TButton;
  19.     Button4: TButton;
  20.                 Button5: TButton;
  21.     DataSource1: TDataSource;
  22.     DBGrid1: TDBGrid;
  23.     EditUserName: TEdit;
  24.     EditUserAge: TEdit;
  25.     Label1: TLabel;
  26.     Label2: TLabel;
  27.     SQLite3Connection1: TSQLite3Connection;
  28.     SQLQuery1: TSQLQuery;
  29.     SQLTransaction1: TSQLTransaction;
  30.     procedure Button1Click(Sender: TObject);
  31.                 procedure Button2Click(Sender: TObject);
  32.                 procedure Button3Click(Sender: TObject);
  33.                 procedure Button4Click(Sender: TObject);
  34.                 procedure Button5Click(Sender: TObject);
  35.                 procedure DBGrid1CellClick(Column: TColumn);
  36.     procedure FormCreate(Sender: TObject);
  37.   private
  38.  
  39.   public
  40.  
  41.   end;
  42.  
  43. var
  44.   Form1: TForm1;
  45.  
  46. implementation
  47.  
  48. {$R *.lfm}
  49.  
  50. { TForm1 }
  51.  
  52. procedure TForm1.FormCreate(Sender: TObject);
  53. begin
  54.   // 进行查询数据的事务处理
  55.   try
  56.     // 进行相关连接操作配置
  57.         self.SQLite3Connection1.Connected:=True;
  58.         self.SQLTransaction1.Active:=True;
  59.         self.SQLQuery1.Active:=True;
  60.     // 进行数据查询操作
  61.           self.SQLQuery1.Open;
  62.   except
  63.     on E:Exception do
  64.     begin
  65.       ShowMessage('抱歉,系统异常('+E.Message+'),查询失败!');
  66.     end;
  67.         end;
  68. end;
  69.  
  70. procedure TForm1.Button1Click(Sender: TObject);
  71. begin
  72.   // 进行新增前的数据检测工作
  73.   if Trim(self.EditUserName.Text) = '' then
  74.   begin
  75.     self.EditUserName.Text:='';
  76.     ShowMessage('用户姓名数据为必填数据!');
  77.     self.EditUserName.SetFocus;
  78.     Exit;    
  79.   end;
  80.   if Trim(self.EditUserAge.Text) = '' then
  81.   begin
  82.     self.EditUserAge.Text:='';
  83.     ShowMessage('用户姓名数据为必填数据!');
  84.     self.EditUserAge.SetFocus;
  85.     Exit;
  86.   end;
  87.   // 进行新增操作的事务处理
  88.   try
  89.     // 进行新增操作前的相关配置信息
  90.     self.SQLite3Connection1.Connected := True;
  91.     self.SQLTransaction1.Active := True;
  92.     self.SQLQuery1.Active := True;
  93.     // 设置新增操作标记
  94.     self.SQLQuery1.Append;
  95.     // 设置相关新增字段
  96.     self.SQLQuery1.FieldByName('name').AsString := Trim(self.EditUserName.Text);
  97.     self.SQLQuery1.FieldByName('age').AsInteger := StrToInt(Trim(self.EditUserAge.Text));
  98.     // 将新增的字段缓存起来
  99.     self.SQLQuery1.Post;
  100.     // 真实应用新增操作
  101.     self.SQLQuery1.ApplyUpdates;
  102.     // 提交缓存的新增记录到数据库中并保持事务继续打开
  103.     self.SQLTransaction1.CommitRetaining;
  104.     // 提示用户新增结果
  105.     ShowMessage('恭喜,新增成功!');
  106.   except
  107.     on E:Exception do
  108.     begin
  109.       // 执行数据库回滚操作
  110.       self.SQLTransaction1.Rollback;
  111.       // 提示用户新增结果
  112.       ShowMessage('抱歉,新增失败!');
  113.     end;
  114.   end;
  115.  
  116. end;
  117.  
  118. procedure TForm1.Button2Click(Sender: TObject);
  119. begin
  120.         // 进行更新操作前的异常处理操作
  121.   try
  122.                 // 进行新增操作前的相关设置操作
  123.     self.SQLite3Connection1.Connected:=True;
  124.     self.SQLTransaction1.Active:=True;
  125.     self.SQLQuery1.Active:=True;
  126.     // 设置当前的模式为编辑状态
  127.     self.SQLQuery1.Edit;
  128.     // 设置要编辑的字段的新的值
  129.     self.SQLQuery1.FieldByName('name').AsString:=Trim(self.EditUserName.Text);
  130.     self.SQLQuery1.FieldByName('age').AsInteger:=StrToInt(Trim(self.EditUserAge.Text));
  131.     // 将欲进行更新的数据缓存起来
  132.     self.SQLQuery1.Post;
  133.     // 将缓存的数据应用到数据库中
  134.     self.SQLQuery1.ApplyUpdates;
  135.     // 进行事物提交操作
  136.     self.SQLTransaction1.CommitRetaining;
  137.     // 提示用户信息
  138.     ShowMessage('恭喜,更新成功!');
  139.     // 清空编辑框数据
  140.     self.EditUserName.Text:='';
  141.     self.EditUserAge.Text:='';
  142.         except
  143.     on E:Exception do
  144.     begin
  145.       ShowMessage('抱歉,系统异常('+E.Message+'),更新失败!');
  146.     end;
  147.         end;
  148. end;
  149.  
  150. procedure TForm1.Button3Click(Sender: TObject);
  151. var
  152.   SQLQueryStr : String;
  153. begin
  154.         // 检测编辑框中是否存在查询数据
  155.   if (Trim(self.EditUserName.Text) = '') and (Trim(self.EditUserAge.Text)='') then
  156.   begin
  157.     ShowMessage('名称和姓名编辑框必须至少填写一项数据才能进行查询操作!');
  158.     Exit;
  159.         end;
  160.   // 设置原始SQL查询语句
  161.   SQLQueryStr := 'SELECT * FROM t_students WHERE 1=1 ';
  162.   self.SQLQuery1.SQL.Text:=SQLQueryStr;
  163.   // 判断是否需要附加名称字段
  164.   if Trim(self.EditUserName.Text) <> '' then
  165.   begin
  166.         SQLQueryStr := SQLQueryStr + 'AND name LIKE :name ';
  167.     self.SQLQuery1.SQL.Text:=SQLQueryStr;
  168.     self.SQLQuery1.ParamByName('name').AsString:='%' + Trim(self.EditUserName.Text) + '%';
  169.         end;
  170.   // 判断是否需要附加年龄字段
  171.   if Trim(self.EditUserAge.Text) <> '' then
  172.   begin
  173.       SQLQueryStr := SQLQueryStr + ' AND age = :age ';
  174.       self.SQLQuery1.SQL.Text:=SQLQueryStr;
  175.       self.SQLQuery1.ParamByName('age').AsInteger:=StrToInt(self.EditUserAge.Text);
  176.         end;
  177.   // 进行查询操作前的异常处理
  178.   try
  179.     // 进行查询前的设置操作
  180.     self.SQLite3Connection1.Connected:=True;
  181.     self.SQLTransaction1.Active:=True;
  182.     self.SQLQuery1.Active:=True;
  183.     // 设置查询的SQL语句操作
  184.     self.SQLQuery1.SQL.Text:=SQLQueryStr;
  185.     // 进行查询操作
  186.     self.SQLQuery1.Close;
  187.     self.SQLQuery1.Open;
  188.     // 提示用户
  189.     ShowMessage('恭喜,查询成功!');
  190.         except
  191.     on E:Exception do
  192.     begin
  193.       ShowMessage('抱歉,系统异常('+E.Message+'),查询失败!');
  194.     end;
  195.         end;
  196. end;
  197.  
  198. procedure TForm1.Button4Click(Sender: TObject);
  199. begin
  200.         // 让用户确认是否进行删除操作
  201.   if MessageDlg('确认删除', '是否确定要执行删除操作?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then
  202.   begin
  203.      ShowMessage('您取消了删除操作!');
  204.      Exit;
  205.         end;
  206.   // 进行删除异常处理操作
  207.   try
  208.     // 进行删除前的配置操作
  209.     self.SQLite3Connection1.Connected:=True;
  210.     self.SQLTransaction1.Active:=True;
  211.     self.SQLQuery1.Active:=True;
  212.     // 设置删除状态标记
  213.     self.SQLQuery1.Delete;
  214.     // 提交删除操作的事务
  215.     self.SQLTransaction1.CommitRetaining;
  216.     // 提示用户删除操作
  217.     ShowMessage('恭喜,删除成功!');
  218.         except
  219.     on E:Exception do
  220.     begin
  221.       ShowMessage('抱歉,系统异常('+E.Message+'),删除失败!');
  222.     end;
  223.         end;
  224. end;
  225.  
  226. procedure TForm1.Button5Click(Sender: TObject);
  227. begin
  228.   // 进行查询数据的事务处理
  229.   try
  230.     // 进行相关连接操作配置
  231.         self.SQLite3Connection1.Connected:=True;
  232.         self.SQLTransaction1.Active:=True;
  233.         self.SQLQuery1.Active:=True;
  234.     // 设置查询语句
  235.     self.SQLQuery1.SQL.Text:='SELECT * FROM t_students';
  236.     // 进行数据查询操作
  237.     self.SQLQuery1.Close;
  238.           self.SQLQuery1.Open;
  239.   except
  240.     on E:Exception do
  241.     begin
  242.       ShowMessage('抱歉,系统异常('+E.Message+'),查询失败!');
  243.     end;
  244.         end;
  245. end;
  246.  
  247.  
  248. procedure TForm1.DBGrid1CellClick(Column: TColumn);
  249. begin
  250.         self.EditUserName.Text:=self.SQLQuery1.FieldByName('name').AsString;
  251.   self.EditUserAge.Text:=self.SQLQuery1.FieldByName('age').AsString;
  252. end;
  253.  
  254. end.
  255.  

   

akjarjash

  • Newbie
  • Posts: 4
For adding new record you do not have you use TQuery, I usually use ExecuteDirect. You can see my demo:
https://forum.lazarus.freepascal.org/index.php/topic,65185.msg496461.html#msg496461

Thank you for your response and efforts. After several attempts, I have successfully created an example using native Lazarus for SQLite3 CRUD operations. The native approach was indeed a bit cumbersome, but I managed to discover some tricks, and it turned out well. I will test the example you recommended when I have the time.

 

TinyPortal © 2005-2018