Solved

using a list of objects, Delphi

Posted on 2013-02-01
3
597 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

929 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

6 Experts available now in Live!

Get 1:1 Help Now