Solved

using a list of objects, Delphi

Posted on 2013-02-01
3
593 Views
Last Modified: 2013-02-02
I have this function in c# and a similar one in java, and  I am trying to implement in Delphi, but can't figure how to do it

basically, instead of writing a bunch of code to build a query, assign it to a query component, clearing and setting the parameters, I want to build a parameterized query, add parameters, and call a function that does the clean up, open, error checking, etc.

the parameters will be different data types.

I did this in c# and java, so there's gotta be a way to do it in Delphi - pretty much the only thing I'm stuck on is the object list.  I haven't used it before and can't seem to find a sample of how to do this, as all the samples seem to use a single object type...

is there a way to do this?
calling logic:

      List<object> parms = new List<object>();
...
            parms.Add(dOrder["CUSTUID"]);//string
            parms.Add(result);//date
            parms.Add(aUID);//long integer
            dbRoutines.execQuery("Update CustDocs Set CustUID = @p1, DateEdited = @p2 where RecordUID = @p3", parms);

Open in new window

the function -

   public static Boolean execQuery([SqlFacet(MaxSize=-1)]String mySQL, List<object> parms)
   {
      Boolean result = true;
	  using (SqlConnection sqlConn =
		 new SqlConnection("Context Connection=True"))
		 {
          SqlCommand sqlCmd = new SqlCommand("SET NOCOUNT ON; " + mySQL, sqlConn);
			sqlCmd.CommandType = CommandType.Text;
			sqlConn.Open();
         for (int x = 0; x <= parms.Count - 1; x++)
        {
           sqlCmd.Parameters.Add(new SqlParameter("@p" + (x + 1).ToString(), parms[x]));//parameterValue)
           
        }

			try
			{
			   sqlCmd.ExecuteNonQuery();
			}
         catch(Exception Ex)
         {
            SqlContext.Pipe.Send("Error Executing query " + Ex.GetType().ToString() + " " + Ex.Message);           
            SqlContext.Pipe.Send(mySQL);
            result = false;
         }
         finally
         {
			   sqlConn.Close();
         }
		 }
      return result;
   }

Open in new window

0
Comment
Question by:ccMcBride
  • 2
3 Comments
 
LVL 32

Accepted Solution

by:
ewangoya earned 500 total points
ID: 38846500
You can use TStringList instead of a TList.
TList will involve extra work of creating the object to be stored and freeing it afterwards

Here is an example using DBExpress components, You can use any other datasets to accomplish the same. Tha basic idea is creating the parameterized query.

procedure ExampleCall;
var
  Params: TStringList;
begin
  Params := TStringList.Create;
  try
    Params.Add('CUSTID=' + dOrder['CUSTUID']);//string
    Params.Add('DateEdited=' +DateTimeToStr(result));//date
    Params.Add('RecordUID=' + aUID);//long integer
    dbRoutines.execQuery('Update CustDocs Set CustUID = :CUSTID, DateEdited = :DateEdited where RecordUID = :RecordUID', Params);
  finally
    FreeAndNil(Params);
  end;
end;

procedure TForm1.ExecQuery(SQLCmd: string; AParams: TStrings);
var
  I: Integer;
  Q: TSQLQuery;
  C: TSQLConnection;
begin
  C : TSQLConnection.Create(nil);
  try
    try
      //Set your connection
      C.Open;
      Q = TSQLQuery.Create(nil);
      try
        Q.SQLConnection := C;
        Q.SQL.Add(SQLCmd);
        Q.Prepared := True;

        for I := 0 to AParams.Count -1 do
          Q.ParamByName(AParams.Names[I]).Value := AParams.ValueFromIndex(I);
        Q.ExecSQL();
      finally
        FreeAndNil(Q);
      end;
    except
      on E: Exception do
      begin
        //Handle your exception
      end;
    end;
  finally
    FreeAndNil(C);
  end;
end;

Open in new window

0
 
LVL 32

Expert Comment

by:ewangoya
ID: 38846504
Use QuotedStr function when assigning the parameters

Q.ParamByName(AParams.Names[I]).Value := QuotedStr(AParams.ValueFromIndex(I));

Open in new window

0
 

Author Closing Comment

by:ccMcBride
ID: 38847106
thank you.  worked right out of the box (once I changed the (I) to [I])....
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now