Monday, October 27, 2008

Delphi Data Access Utility

I want to share this one out as if
1. Any one like to use it, be my guest.
2. Any one has any comment on it, please :)
Note: I am a biginner in Delphi, so please manage your expectation. Thanks.

[
unit LIB_DATA_ACCESS;

interface

uses
  Windows, SysUtils, Variants, DB, ADODB;

const
  CONNECTION_STRING='Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data\test.mdb;Persist Security Info=False;Jet OLEDB:Database Password=******';

Type
  TResultSet = Array of Array of Variant;

function ExecuteQuery( Conn:TADOConnection; Query:TADOQuery; Sql : String;
    Parameters : Array of String;
    Values : Array of Variant): TResultSet;
function ExecuteUpdate( Conn:TADOConnection; Query:TADOQuery; Sql : String; 
    Parameters : Array of String; Values : Array of Variant ): Integer;

implementation


function ExecuteQuery(Conn:TADOConnection; Query:TADOQuery; Sql : String;
    Parameters : Array of String;
    Values : Array of Variant): TResultSet;
var
  tempArray : TResultSet;
  row_index : Integer;
  col_index : Integer;
  i : Integer;
  ColumnSize : Integer;
begin

  Conn.ConnectionString := CONNECTION_STRING;
  Conn.LoginPrompt := False;
  Query.Connection := CONN;
  if Query.Active then
  begin
    Query.Close;
  end;

  try

    Query.SQL.Clear;
    Query.SQL.Add(Sql);

    if Length(Parameters) > 0 then
    begin
      for  i := 0 to (Length(Parameters) - 1) do
      begin
        Query.Parameters.ParamByName(Parameters[i]).Value := Values[i];
      end;
    end;

    Query.Open;
    SetLength(tempArray, Query.RecordCount);

    row_index := 0;

    while not Query.Eof do
    begin
      ColumnSize := Query.Recordset.Fields.Count;
      SetLength(tempArray[row_index], ColumnSize);

      col_index := 0;
      for i := 0 to (ColumnSize - 1) do
      begin
        tempArray[row_index][col_index] := Query.Recordset.Fields[i].Value;
        col_index := col_index + 1;
      end;

      row_index := row_index + 1;
      Query.Next;
    end;
  finally
    Query.Close;
    Conn.Close;
    Result := tempArray;
  end;
end;

function ExecuteUpdate( Conn:TADOConnection; Query:TADOQuery; Sql : String;
    Parameters : Array of String;
    Values : Array of Variant): Integer;
var
  i : Integer;
begin
  Conn.ConnectionString := CONNECTION_STRING;
  Conn.LoginPrompt := False;
  Query.Connection := CONN;
  if Query.Active then
  begin
    Query.Close;
  end;

  try
    Query.SQL.Clear;
    Query.SQL.Add(Sql);

    if Length(Parameters) > 0 then
    begin
      for  i := 0 to (Length(Parameters) - 1) do
      begin
        Query.Parameters.ParamByName(Parameters[i]).Value := Values[i];
      end;
    end;

//  Query.Open;
    Result := Query.ExecSQL;

  finally
    Query.Close;
    Conn.Close;
  end;
end;

end.
]

No comments: