Archive
Archive for July 4, 2013
Bling up your database coding
July 4, 2013
Leave a comment
Class helpers can really bling up your database programming. If you like your database management neatly isolated in classes rather than scattered on a form in the shape of components, then this will really make things easier:
type TFirebirdHelper = class helper for TIBDatabase public function makeQuery(out aQuery:TIBQuery):Boolean; End; function TFirebirdHelper.makeQuery(out aQuery:TIBQuery):Boolean; var mQuery:TIBQuery; begin result:=False; aQuery:=NIL; try mQuery:=TIBQuery.Create(NIL); except //just a stub, you would log at this point on exception do; end; try mQuery.Database:=self; mQuery.Transaction:=self.transaction; except //same here, just a stub on exception do freeAndNil(mQuery); end; result:=assigned(mQuery); if result then aQuery:=mQuery; end;
And you use it with minimal gap between creation and destruction like this, COM style:
if IBDatabase1.makeQuery(mQuery) then begin try mQuery.sql.add('your sql goes here'); try mQuery.executeSQL; except //Log and handle errors here end; finally mQuery.free; end; end;
I use the same technique to isolate common sql stuff like “count of” and “max(field)” and so on.
With enough helpers in place, writing rock solid database wrappers is both fun and easy! And it’s easy to port as well, re-write the core unit and the rest of your app doesnt need to know “where” the data comes from. It only needs to know about TDataset and other abstractions.
Abstract, abstract and abstract