Reputation: 725
I am pretty new to delphi and I would like to ask how can I create a correct SQL statement / SQL string in delphi.
I have tried something like this:
sql:='use [TestovaciaDb] INSERT INTO [dbo].[client]([Meno],[Priezvisko]) VALUES('+name+','+surname+')';
I am using MS SQL server 2012
But I am getting a exception there. Thank you
EDIT:
meno
and priez
are variables with values from TEdit1
and TEdit2
:
meno:= Edit1.Text;
priez:= Edit2.Text;
Upvotes: 0
Views: 1943
Reputation: 125767
Use parameterized queries. You set the database in your ConnectionString, so you don't need to `use' it in your query.
ADOQuery1.SQL.Text := 'INSERT INTO [dbo].[client] ([Meno],[Priezvisko]) ' +
'VALUES(:Meno, :Priezvisko)';
ADOQuery1.Parameters.ParamByName('Meno').Value := Edit1.Text;
ADOQuery1.Parameters.ParamByName('Priezvisko').Value := Edit2.Text;
ADOQuery1.ExecSQL;
Upvotes: 7
Reputation: 1943
Remove the use [xxx]
at the begining of the statement. The connection you use must be already configured to point to the correct database. Just like many others said, avoid creating your sentences by using constants, instead, use paramenters.
Upvotes: 1
Reputation: 324
http://docwiki.embarcadero.com/Libraries/XE3/en/System.SysUtils.QuotedStr
Use QuotedStr function. For example
sql:='use [TestovaciaDb] INSERT INTO [dbo].[client]([Meno],[Priezvisko]) VALUES('+QuotedStr(name)+','+QuotedStr(surname)+')';
Use QuotedStr to convert the string S to a quoted string. A single quotation mark (') is inserted at the beginning and end of S, and each single quotation mark in the string is repeated. To remove the quotation marks from a quoted string, use the AnsiDequotedStr routine.
Upvotes: 0