1

I wrote code like this :

sql1 :='select sum(jumlah) as debet from kasir_kas_transaksi where flag in (1,3) and tanggal = to_date('+quotedstr(after)+','+quotedstr('dd-mm-yyyy')+')';

with zquery1 do begin
  close;
  sql.clear;
  sql.Add(sql1);
  execSQL;
end;
edit1.Text:=zquery1.fieldbyname('debet').asstring;

then an error occured saying field 'debet' does not exist. is there something wrong in the code? I am using delphi 7 and zeos as connection, as well as oracle 11g as db. Thank you!

Ken White
  • 123,280
  • 14
  • 225
  • 444
mizkyd
  • 75
  • 1
  • 11

1 Answers1

4

Use Open, not ExecSQL. ExecSQL is for queries that don't return result sets (INSERT, DELETE, and UPDATE). Open is for queries that return rows. You also don't need to use SQL.Clear; and then SQL.Add(); - you can just set SQL.Text directly instead.

(You should stop using with; that's a different topic, but I left it here because it's your code and not mine.)

with ZQuery1 do
begin
  SQL.Text := sql1;
  Open;
end;
Edit1.Text := ZQuery1.FieldByName('debet').AsString;

And as a note, stop concatenating SQL and use parameters instead. String concatenation with user input leaves you wide-open for SQL injection. Google Little Bobby Tables to find out why that's a bad thing if you don't know already. You can find an example here of writing your code using parameters instead.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • thank you so much for you help. I am super new at coding stuffs so I lack lots of basics. again, thanks! – mizkyd Nov 30 '17 at 03:59
  • but like, can you educate me a bit about the with? It would help for future coding I'm going to make. thank you again! – mizkyd Nov 30 '17 at 04:01
  • 2
    Yes. Stop using `with`. It can cause hard-to-find bugs. It's much better to remove it and just type the extra characters than it is to waste hours trying to solve a problem caused by unexpected results of a with statement. – Ken White Nov 30 '17 at 04:03
  • To expand on @Ken's comment: `with` was very useful in old Pascal, where it could be used to make certain pieces of code more efficient. But that was in the days of simple, non-optimizing compilers and when Pascal did not have any object oriented extensions. These days, especially because of OO with much more complex scopes, `with` can become a big problem and should be avoided. – Rudy Velthuis Nov 30 '17 at 12:52
  • @mizkyd you used `with` in the code you posted. You did so without knowing what it does? – lurker Nov 30 '17 at 21:14
  • @mizkyd: [Why should I not use "with" in Delphi?](https://stackoverflow.com/q/71419/62576) – Ken White Nov 30 '17 at 23:29