如何在Delphi的SQLite表中插入整数值

Nin*_*are 1 delphi sqlite delphi-xe3

我试图SQLite在Delphi的表中插入整数值.
表中emp usergroup_id是整数label,description是字符串数据类型.
我的代码如下:

var
  gid: Integer;
  sdescription,ldescription: String;
begin
  sdescription := RzEdit1.Text;
  ldescription := RzMemo1.Text;
  gid := Integer(RzComboBox1.Items.Objects[RzComboBox1.Items.IndexOf(gname)]);

  try
    SQLConnection1.Connected := true;
    SQLMonitor1.Active := True;
    sSql := 'INSERT INTO emp(usergroup_id, label, description) VALUES (gid,''' + sdescription + ''',''' + ldescription + ''' )';
    SQLConnection1.ExecuteDirect(sSql);

  except
    on E: EDatabaseError do
      ShowMessage('Exception raised with message' + E.Message);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误Unknown column gid.
当我用固定的整数值而不是变量尝试这样的东西时,它可以工作:

sSql := 'INSERT INTO emp(usergroup_id, label, description) VALUES (1,''' + sdescription + ''',''' + ldescription + ''' )';
Run Code Online (Sandbox Code Playgroud)

它将值成功插入表中.
如何gid使用上面的查询将整数值插入到数据库中.什么是正确的格式?

kob*_*bik 6

gid将成为SQL语句的一部分(因此错误:) Unknown column gid.
您需要使用Delphi gid变量来构造SQL语句(就像您使用sdescription和一样ldescription):

sSql := 'INSERT INTO emp(usergroup_id, label, description) VALUES (' + InttoStr(gid) + ', ''' + sdescription + ''',''' + ldescription + ''' )';
Run Code Online (Sandbox Code Playgroud)

如果你曾经使用过参数,那么你就不会有这么乱的查询/代码(这也需要SQL注入等等),例如:

qry := TSQLQuery.Create(nil); // or what ever TQuery component you use in your framework
try
  qry.SQLConnection := SQLConnection1;
  qry.SQL.Text := 'INSERT INTO emp(usergroup_id, label, description) VALUES (:usergroup_id, :label, :description)';
  qry.Params.ParamByName('usergroup_id').Value := gid;
  qry.Params.ParamByName('label').Value := sdescription;
  qry.Params.ParamByName('description').Value := ldescription;
  qry.ExecSQL;
finally
  qry.Free;
end;
Run Code Online (Sandbox Code Playgroud)

  • 一如既往,参数+1;) (4认同)