Home > Mobile >  I receive an Insert Into error with this code any solution?
I receive an Insert Into error with this code any solution?

Time:08-02

if (conpassedt.text = '') or (regpassedt.text = '') or (regaccedt.text = '') or (regpassedt.text <> conpassedt.text) then
  begin
    showmessage('Please fill in all fields for input and confirm passwords match');
  end else
  begin
    DM.qryDB.sql.clear;
    DM.qrydb.sql.add('INSERT INTO tblUsers(AccountName, Password) ');
    DM.qrydb.sql.add('VALUES ("'  regaccedt.text  '", "'   THashMD5.GetHashString(regpassedt.text)   '")');
    DM.qrydb.ExecSQL;
  end;

CodePudding user response:

Modern versions of Delphi with Firedac have overloaded versions of various SQL methods to allow removal of a lot of the boilerplate in your question. Also as already mentioned in comments use parameters vs constructing a string.

  FDQuery1.ExecSQL('INSERT INTO tblUsers(AccountName, Password) VALUES (:AccountName, :Password);',
                   [regaccedt.text,THashMD5.GetHashString(regpassedt.text)],
                   [ftWideString,ftWideString]);

CodePudding user response:

Most likely, your DB requires single quotes instead of double quotes on string literals, eg:

DM.qrydb.sql.add('INSERT INTO tblUsers(AccountName, Password) ');
DM.qrydb.sql.add('VALUES ('''   regaccedt.text   ''', '''   THashMD5.GetHashString(regpassedt.text)   ''')');

In which case, you should use QuotedStr() instead to handle quoting and escaping for you (which will better help you avoid SQL Injection attacks properly), eg:

DM.qrydb.SQL.Add('INSERT INTO tblUsers (AccountName, Password) ');
DM.qrydb.SQL.Add('VALUES ('   QuotedStr(regaccedt.text)   ', '   QuotedStr(THashMD5.GetHashString(regpassedt.text))   ')');

Though, you really should use a parameterized query instead, and let the DB engine work out any necessary quoting and escaping that it needs, eg:

DM.qrydb.SQL.Add('INSERT INTO tblUsers (AccountName, Password) ');
DM.qrydb.SQL.Add('VALUES (:PAccountName, :PPassword)');
DM.qrydb.ParamByName('PAccountName').AsString := regaccedt.text;
DM.qrydb.ParamByName('PPassword').AsString := THashMD5.GetHashString(regpassedt.text);
  • Related