SQLite - 如何使用预准备语句?

时间:2014-05-21 21:01:12

标签: sql delphi sqlite

我正在尝试Tim Anderson's SQLite3 Wrapper for Delphi,我目前在使用预备语句时遇到问题。我无法使用extended variant by SV因为我需要与Delphi 6保持兼容。

这是我到目前为止所尝试的:

var
  sldb: TSQLiteDatabase;
  sltb: TSQLIteTable;
  q: TSQLiteQuery;
begin
  sldb := TSQLiteDatabase.Create(ADBFile);

  if not sldb.TableExists('vmd_nodes') then
  begin
    sldb.execsql('CREATE TABLE vmd_nodes (content_date BLOB, node_type_oid OID, content_type_pod OID, update_ts TIMESTAMP, create_ts TIMESTAMP, node_guid GUID PRIMARY KEY, parent_guid GUID);');
  end;

  // Try #1: hardcoded (works)
  sltb := slDb.GetTable('SELECT * FROM vmd_nodes WHERE node_guid = "asd"');
  try
    showmessage(inttostr(sltb.Count)); // Output: 1
  finally
    sltb.Free;
  end;

  // Try #2 (does not work)
  sltb := slDb.GetTable('SELECT * FROM vmd_nodes WHERE node_guid = ?', ['asd']); // ???
  try
    showmessage(inttostr(sltb.Count)); // Output: 0
  finally
    sltb.Free;
  end;

  // Try #3
  sldb.AddParamText('guid', 'asd'); // why is AddParamText member of sldb instead of q ???
  q := sldb.PrepareSQL('SELECT * FROM vmd_nodes WHERE node_guid = :guid');
  sldb.AddParamText('guid', 'asd'); // why is AddParamText member of sldb instead of q ???
  ShowMessage(q.SQL); // SELECT * FROM vmd_nodes WHERE node_guid = :guid => Nothing was replaced
  sltb := q; // How to get a TSQLIteTable out of the TSQLiteQuery ?
end;

1 个答案:

答案 0 :(得分:4)

根据(有些奇怪的表达)docs,您首先添加参数,然后使用GetTable和SQL一起获取结果,例如;

sldb.AddParamText(':guid', 'asd');
sltb := sldb.GetTable('SELECT * FROM vmd_nodes WHERE node_guid = :guid');