1
votes

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

1 Answers

6
votes

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;