1

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 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Bonus code & detailed answer helped, however getting error like parameter usergroup_id not found, same with label and description. I am using TSQLQuery descendant of TQuery and modified code as follows qry.Params.ParamByName('usergroup_id').Value := gid;
As always, +1 for parameters ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.