How to insert integer value into SQLite table at Delphi

放肆的年华 提交于 2019-12-11 11:22:52

问题


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;

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 + ''' )';

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


回答1:


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 + ''' )';

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;


来源:https://stackoverflow.com/questions/19220938/how-to-insert-integer-value-into-sqlite-table-at-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!