A better way of passing parameters to a TADOStoredProc (Delphi)

后端 未结 4 875
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 11:56

I am needing to convert a large amount of SQL queries into stored procedures. I have some code that updates about 20 or 30 values at one time in one Delphi procedure. I can

相关标签:
4条回答
  • 2021-01-02 12:34

    This is the shortest I know:

    stored_procedure.Parameters.ParamByName('@SSN').Value := edtSSN.text;
    

    Note, you need to assign the stored_procedure.Connection and call stored_procedure.Parameters.Refresh; before doing this

    0 讨论(0)
  • 2021-01-02 12:38

    ADO will create the parameters for you, you just need to call Refresh on the parameters object:

     SP.Connection := SqlConnection; // must be done before setting procedure name
     sp.ProcedureName := 'MyStoredProc';
     sp.Parameters.Refresh; // This will create the parameters for you as defined in SQL Server
     sp.Parameters.ParamByName('@SSN'').Value  := SSN; // params now exist
    

    etc

    If any parameters are output you will need to set them explicitly:

       sp.Parameters.ParamByName('@ReturnValue').Direction := pdInputOutput;
    
    0 讨论(0)
  • 2021-01-02 12:44

    There's an accepted answer :-), but I want to point you to simpler and easier way to define and use the parameters with one line :

    stored_procedure.Parameters.CreateParameter('SSN',ftString,pdInput,30,edtSSN.text);
    

    It's simple and flexible, because you can define the input and output parameters with same line.

    and from Delphi help:

    function CreateParameter(const Name: WideString; DataType: TDataType;
        Direction: TParameterDirection; Size: Integer; 
        Value: OleVariant): TParameter;
    
    0 讨论(0)
  • 2021-01-02 12:50

    This doesn't cause a memory leak. stored_procedure will clean up its parameters. You can confirm this with FastMM by adding the following to your .dpr:

      ReportMemoryLeaksOnShutdown := True;
    

    First, I'd get rid of the "with" statement. It can lead to more problems and less readable code.

    I'd create a helper method that accepts a stored procedure, a parameter name and a parameter value, which will make your code more manageable.

    AddParam(stored_procedure, '@SSN', edtSSN.text);
    AddParam(stored_procedure, '@FirstName', edtFirstName.Text);
    AddParam(stored_procedure, '@LastName', edtLastName.Text);
    AddParam(stored_procedure, '@UserRID', GetRIDFromCombo(cbUser));
    
    0 讨论(0)
提交回复
热议问题