If you insist on using string concatenation (despite all advice to the contrary), at least eliminate the noise of trying to count the single quotes and use QuotedStr (once again, the link is to XE4 documentation, but the function exists in Delphi 7 as well).
The same information I provided in my answer to your other question also applies here. Name
is still a reserved word in MS Access, and therefore still needs to be surrounded by []
. It will need that every single time you use it, which is also why I suggested you change the field name before you got too far along.
The code you posted shows the ADOQuery being freed at the end, but does not show it being created. I've added that code so that it makes sense; you'll need to replace the connection string with one to your database. I've also changed the name of the ADOQuery from ADOQuery1
(which will conflict with any existing ADOQuery on your form with the default name) because your code appears to be creating a new one for just this block of code. If in fact you're using one already on the form or datamodule, you should delete the try
, Create
, ConnectionString
, and lines finally
, Free
, and the next end
, and rename all of the TempQuery
variables back to ADOQuery1
.
var
NumRows: Integer;
TempQuery: TADOQuery;
begin
TempQry := TADOQuery.Create(nil);
try
TempQuery.ConnectionString := 'Use your own connection string here';
TempQuery.SQL.Text := 'SELECT * FROM Admins WHERE [Name] = ' +
QuotedStr(Edtname.text);
TempQuery.Open;
if TempQuery.IsEmpty then
begin
ShowMessage('User ' + EdtName.Text + ' not found!');
Exit;
end;
TempQuery.Close;
TempQuery.SQL.Text := 'DELETE FROM Admins WHERE [Name] = ' +
QuotedStr(EdtName.Text);
TempQuery.ExecSQL;
NumRows := TempQuery.RowsAffected;
ShowMessage(IntToStr(NumRows) + ' were deleted');
finally
TempQuery.Free;
end;
end;
Once again, however, this would be better using parameterized queries. It only adds two additional lines of code, and eliminates the security risks involved with SQL injection at the ExecSQL
line:
TempQuery.SQL.Text := 'SELECT * FROM Admins WHERE [Name] = :UserName';
TempQuery.Parameters.ParamByName('UserName').Value := EdtName.Text;
TempQuery.Open;
TempQuery.SQL.Text := 'DELETE FROM Admins WHERE [Name] = :UserName';
TempQuery.Parameters.ParamByName('UserName').Value := EdtName.Text;
TempQuery.ExecSQL;