Friday, 19 May 2017

mysql - Insert into SQL syntax error delphi



I am wanting to insert a record into a database table (website) by using a procedure with parameters. The SQL code has been tested in mysql workbench and works properly to insert new data. However, with delphi i am getting an 'SQL Syntax error near [insert whole line of code here]'. I was wondering if one of you could tell me where I'm going wrong. Thanks again.




procedure TNewWebsite.InsertData(WID, D, T, Wh, Dr, Od, Rd, Rc, Pm, OStat,  Cstat, Rstat, N, U1, P1, P2, PStat, CID : string);
begin
WebsiteTable.WebsiteQuery.SQL.Add('INSERT INTO website VALUES ( '+WID+', '''+D+''', '''+T+''', '''+Wh+''', '''+D+''', '''+Od+''', '''+Rd+''', '+Rc+', '''+Pm+''', '+Ostat+', '+Cstat+', '''+Rstat+''', '''+N+''', '''+U1+''', '''+P1+''', '''+P2+''', '+Pstat+', '+CID+';)');
WebsiteTable.WebsiteQuery.Open;
end;

Answer



You have quite a few problems in your code.




A) Don't exaggerate with function parameters, if you have a lot of variables, assemble them in a record or class depending on your needs.



B) Your SQL code is vulnerable for SQL injection. You probably never heard of SQL injection, please Google it or read this really good answer. The solution against SQL injection is to use parameters (see my code example). An added bonus is that your SQL statement will be human readable, and less error prone.



C) The Open function is only used in conjunction for queries that return a result set, like SELECT statements. For INSERT, DELETE and UPDATE statements, you need to use the ExecSQL function.



Sanitized code:



interface


type
TMyDataRecord = record
WID : String;
D : String;
T : String;
Wh : String;
Dr : String;
Od : String;
Rd : String;
Rc : String;

Pm : String;
OStat : String;
Cstat : String;
Rstat : String;
N : String;
U1 : String;
P1 : String;
P2 : String;
PStat : String;
CID : String;

end;
...
implementation

procedure TNewWebsite.InsertData(Data : TMyDataRecord);

var
SQL : String;

begin

SQL := 'INSERT INTO website VALUES (:WID, :D1, :T, :Wh, :D2, :Od, :Rd, :Rc',+
'Pm, :Ostat, :Cstat, :Rstat, :N, :U1, :P1, :P2, :Pstat, :CID)';
WebsiteTable.WebsiteQuery.ParamCheck := True;
WebsiteTable.WebsiteQuery.SQL.Text := SQL;
WebsiteTable.WebsiteQuery.Params.ParamByName('WID').AsString := Data.WID;
WebsiteTable.WebsiteQuery.Params.ParamByName('D1').AsString := Data.D;
...// rest of parameters
WebsiteTable.WebsiteQuery.Params.ParamByName('CID').AsString := Data.CID;
WebsiteTable.WebsiteQuery.ExecSQL;
end;


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...