如何在Delphi的SQLite表中插入整数值 [英] How to insert integer value into SQLite table at Delphi

查看:144
本文介绍了如何在Delphi的SQLite表中插入整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Delphi的 SQLite 表中插入整数值。

在表 emp usergroup_id 是整数,而 label 描述

我的代码如下:

I am trying to insert integer value in my SQLite table at Delphi.
In table emp usergroup_id is integer and label, description are string data type.
My code is as follows:

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;

它给我一个错误,因为 Unknown column gid

当我尝试使用固定整数值而不是变量进行类似操作时,它会起作用:

It is giving me an error as Unknown column gid.
When I tried something like this with fixed integer value instead of variable it works:

sSql := 'INSERT INTO emp(usergroup_id, label, description) VALUES (1,''' + sdescription + ''',''' + ldescription + ''' )';

将值成功插入表中。

如何插入 gid 进入具有上述查询的数据库。正确的格式是什么?

It inserts values successfully into table.
How to insert integer value of gid into database with above query. What would be the proper format?

推荐答案

您的 gid 成为一部分SQL语句的名称(因此错误: Unknown column gid )。

您需要使用Delphi gid 变量来构造SQL语句(就像您使用 sdescription ldescription 一样):

Your gid becomes a part of the SQL statement (hence the Error: Unknown column gid).
You need to use the Delphi gid variable to construct the SQL statement (just like you did with sdescription and ldescription):

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

如果您会使用 Parameters 不会有这样凌乱的查询/代码(也可能受到SQL注入等)。例如:

If You would have used Parameters you wouldn't have such a messy query/code (which is also subject to SQL injection, etc..) e.g.:

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;

这篇关于如何在Delphi的SQLite表中插入整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆