My blog has moved!

You should be automatically redirected in 6 seconds. If not, visit
http://perevoznyk.wordpress.com
and update your bookmarks.

Tuesday, March 07, 2006

Simple way to execute ADO Query

With this unit you can create and execute queries without using ADO components. The size of application is dramatically smaller....



unit ADOSupport;

interface

uses
Windows,
SysUtils,
ActiveX,
ADOInt;

function ExecuteADOSQL(ConnectionString : string; UserName : string; Password : string; command : string) : integer;
function CreateADOConnection(ConnectionString : string; UserName : string; Password : string) : _Connection;
procedure ExecuteADOQuery(Connection : _Connection; command : string);
procedure CloseConnection(Connection : _Connection);

implementation

function Succeeded(Res: HResult): Boolean;
begin
Result := Res and $80000000 = 0;
end;

function CreateADOObject(const ClassID: TGUID): IUnknown;
var
Status: HResult;
FPUControlWord: Word;
begin
asm
FNSTCW FPUControlWord
end;
Status := CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER, IUnknown, Result);
asm
FNCLEX
FLDCW FPUControlWord
end;
if (Status = REGDB_E_CLASSNOTREG) then
raise Exception.Create('Class creation error') else
if not Succeeded(Status) then
Raise Exception.Create('OLE Exception');
end;

function ExecuteADOSQL(ConnectionString : string; UserName : string; Password : string; command : string) : integer;
var
FConnectionObject: _Connection;
VarRecsAffected: OleVariant;
begin
FConnectionObject := CreateADOObject(CLASS_Connection) as _Connection;
FConnectionObject.Open(ConnectionString, UserName, Password, 0);
FConnectionObject.Execute(command, VarRecsAffected, 1 + $00000080);
FConnectionObject.Close;
Result := VarRecsAffected;
end;

function CreateADOConnection(ConnectionString : string; UserName : string; Password : string) : _Connection;
begin
Result := CreateADOObject(CLASS_Connection) as _Connection;
Result.Open(ConnectionString, UserName, Password, 0);
end;


procedure ExecuteADOQuery(Connection : _Connection; command : string);
var
VarRecsAffected: OleVariant;
begin
Connection.Execute(command, VarRecsAffected, 1 + $00000080);
end;

procedure CloseConnection(Connection : _Connection);
begin
Connection.Close;
end;

end.