delphi3000.com - the free delphi knowledge platform
delphi3000.com - the free delphi knowledge platform
487 Users Online NOW
Have a look at your member-status

connecting people's knowledge


  - Recent ArticlesRSS feed for Recent Articles on delphi3000.com
  - List of All Articles
  - Top Viewed Articles
  - Articles (+Attachem.)
  - Articles Of Interest
  - Categories
  - Top Uploader
  - Search
  - Index

  - My Home
  - Submit an Article
  - My Articles
  - My Personal Data
  - My Bookmarks
  - Activities
  - Login/Logout

  - Sign Up
  - Why Sign Up
  - Newsletter

  - Press
  - Advertise

  - Contact
  - Feedback





Community
Borland
ClubeDelphi
Dr. Bob
UK-BUG
Delphi Meetings
Planeta Delphi



Loremo - the 1.5 liter car coming in 2009




Startblatt.de






Share this article with friendsShare this article with friends
Rate this articleRate this article - to keep the quality of delphi3000.com !
Comment this article or read through previous comments (2)


SQL without burocracyGo to Josir Gomes's websiteFormat this article printer-friendly!Bookmark function is only available for registered users!
How to quickly run SQLs without dropping components on your form
Product:
Delphi all versions
Category:
DB-General
Skill Level:
Scoring:
Last Update:
10/02/2002
Search Keys:
delphi delphi3000 article borland vcl code-snippet BDE DbExpress SQL
Times Scored:
1
Visits:
4681
Uploader: Josir Gomes
Company: JSK Consultoria e Treinamento
Reference: N/A
 
Question/Problem/Abstract:
If you write database software, you can admit that it's not an easy thing to drop tquerys (or tsimpledataset) components every time you must run a SQL query. It has to be a quicker way!
Answer:



Sometimes, in a large database application, you must run small SQLs in order to continue your business logic. In a regular BDE environment, you must drop a TQUERY component, write the SQL code in it and then write

Query1.Close;
set parameters, blah, blah, blah
Query1.Open;

Do you agree that this is not very clever and this technic breaks your logic apart ? In other IDEs, like Oracle Developer 2000, you write your SQL directly on your code. Imagine this code:

  InvoiceTotal := IntegerSQL('SELECT SUM(TOTAL) FROM INVOICE WHERE SQINVOICE = %d',[ InvoiceNumber ]);

or

  SupplierName := StringSQL('SELECT NAME FROM SUPPLIER WHERE SUPPLIERCODE = ''%s''',[ SupplierCode ]);

or either

  SQLExec('UPDATE INVOICE SET TYPE = ''%s'' WHERE SQINVOICE = %d',
          [ InvType, InvoiceNumber ]);

So I wrote this simple unit in order to easy my work days:

unit BDELib;

interface

uses Classes, SysUtils, DbiProcs, DbiTypes,
     Db, BDE, DbTables, DbConsts, StdLib, TypInfo;

procedure SetMaxRows( Qry: TQuery; const Rows: longint );

Function BooleanSQL(const SQLCommand: string;
                    const Args: array of const;
                    const DBName : string = '') : boolean;

function SQLCursor( const SQLCommand:String;
                    const Args: array of const;
                    const DbName: String = ''): TQuery;

function SQLRestrictRows( const SQLCommand:String;
                          const Args: array of const;
                          const MaxRow: longint;
                          const DBName : string = '' ): TQuery;

function IntegerSQL( const SQLCommand: String;
                     const Args: array of const;
                     const DBName : string = '' ):longint;

function StringSQL( const SQLCommand: String;
                    const Args: array of const;
                    const DBName : string = '' ):String;

function NumberSQL( const SQLCommand: String;
                    const Args: array of const;
                    const DBName : String = '' ): double;

procedure SQLExec( SQLCommand: String;
                   const Args: array of const );

var MainDatabase: TDatabase;

implementation

function SQLCursor( const SQLCommand:String;
                    const Args: array of const;
                    const DbName: string ): TQuery;

var QueryTemp: TQuery;
    rslt: DbiResult;

begin

  QueryTemp := TQuery.Create( nil );
  with QueryTemp do
  try

    DatabaseName := IfDefault(DbName,'',MainDatabase.DatabaseName);

    if GlobalMaxRows > 0 then
      begin
        rslt := DbiValidateProp( hDBIObj( Handle ), curMAXROWS, True);
        if (rslt = DBIERR_NONE) then
           Check( DbiSetProp( hDBIObj( Handle ), curMAXROWS, GlobalMaxRows ));
      end;

    SQL.Add( Format( UpperCase(SQLCommand), Args) );
    Open;
    Result := QueryTemp;
  except
    on E: Exception do
    begin
      QueryTemp.Free;
      raise;
    end;
  end;
end;

function SQLRestrictRows( const SQLCommand:String;
                          const Args: array of const;
                          const MaxRow: longint;
                          const DbName: string ): TQuery;
begin
  try
    GlobalMaxRows := MaxRow;
    Result := SQLCursor( SQLCommand, Args, DbName );
  finally
    GlobalMaxRows := 0;
  end;
end;

function BooleanSQL(const SQLCommand:String;
                    const Args: array of const;
                    const DbName: string ):boolean;
begin
  with SQLRestrictRows(SQLCommand, Args, 1, DbName) do
    try
      Result := not Eof;
    finally
      Free;
    end;
end;

function IntegerSQL( const SQLCommand: String;
                     const Args: array of const;
                     const DbName: string ):longint;
begin
  with SQLRestrictRows(SQLCommand, Args,1, DbName) do
   try
     if Eof or Fields[0].IsNull then
        Result := 0
     else
        Result := Fields[ 0 ].AsInteger;
   finally
     Free;
   end;
end;

function StringSQL( const SQLCommand: String;
                     const Args: array of const;
                     const DbName: string ):String;
begin
  with SQLRestrictRows(SQLCommand, Args,1, DbName) do
   try
     if Eof or Fields[0].IsNull then
        Result := ''
     else
        Result := Fields[ 0 ].AsString;
   finally
     Free;
   end;
end;

function NumberSQL(const SQLCommand: String;
                     const Args: array of const;
                     const DBName : string ): double;
begin
  with SQLRestrictRows(SQLCommand, Args,1, DBName) do
  try
    if Eof or Fields[0].IsNull then
       Result := 0
    else
       Result := Fields[ 0 ].AsFloat;
  finally
    Free;
  end;
end;

procedure SQLExec( SQLCommand: String;
                   const Args: array of const );
begin
  SQLCommand := Format(SQLCommand, Args);
  Check( DbiQExecDirect( MainDatabase.Handle, qryLangSQL,
                         PChar( SQLCommand ), nil) );
end;

end;

Note 1: The variable MainDatabase is just a shortcut - in order to use it, assign your current database to it before start any call. But this  technic is not wise if you work with more than one session opened.

Note 2: The RestrictedRows parameter just work for Oracle driver.
Note 3: This techinque can easily be tranlated to DbExpress or any other engine.

Health and Freedom,
Josir Gomes





Please rate this article!
Skill level:
BeginnerExpert

Useful:
No!Very!

Overall rating:
PoorExcellent



Comments to this article
Write a new comment
See Also
    Mike Heydon (Oct 4 2002 3:04PM)

I like the Format() array of const idea in the select. I have updated my article :http://www.delphi3000.com/articles/article_2293.asp
to give overloaded options to my AsString.AsInteger etc. methods.

My Class implements: (TSQLCommand)

Support for ORACLE and MS-SQL
DateTimes Inserts and Updates are handled differently by
these systems. Would be grateful if anyone has Informix or DB2 that can add functionality to the class for me  :)

DebugMode which display the errant SQL statement and allows
modification to correct it. The modified code can be cut to
clipboard and is automatically saved to file LastSqlErr.sql on
closing debug window.

Automatic error message dialogs or user handled errors via
property LastErrorMess and LastSqlCommand.

Single value returns implemented AsString,AsInteger etc.

INSERT,UPDATE and DELETE super macro methods.

Respond

Other techniques.
    Abdulaziz Jasser (Oct 2 2002 7:59AM)

http://www.delphi3000.com/articles/article_2937.asp
Respond














 
Sign up to consume product discounts for Bronze memberships !

read more


  Visit our Sponsor

 

  Community Ad of
L. Rosenstein
 
   














 







     
  Copyright © 2000 - 2007 delphi3000.com - All rights reserved. Terms of use. || Privacy
delphi3000.com is a service by bluestep.com IT-Services GmbH (Vienna)