dotConnect Universal Documentation
In This Topic
    Using Parameters
    In This Topic

    dotConnect Universal enhances SQL handling capabilities with usage of parameters in SQL queries. You can make execution of a query or stored procedure very flexible using several simple techniques. This article describes some basics you must be acquainted with when working with parameters in dotConnect Universal, as well as parameters synchronization and some nuances related to usage of stored procedures.

    The article consists of following sections:

    Parameters basics

    In general, parameter is a placeholder for a variable that contains some value of some type when executing a general-purpose query, or arguments and return values when a stored procedure is executed. Parameter is represented by Devart.Data.Universal.UniParameter class. All parameters that take part in query execution constitute a collection that can be accessed through UniCommand.Parameters property.

    Two kinds of parameters exist: named and unnamed.

    Unnamed parameters can be specified as '?' symbol. The following query

        insert into dept (deptno, dname, loc) values (?, ?, ?)
    

    declares that three parameters are required to run the query properly. To set parameters for this query you can use the next code:

    UniCommand uniCommand1;
    ...
    uniCommand1.CommandText = "insert into dept (deptno, dname, loc) values (?, ?, ?)";
    uniCommand1.Parameters.Add("param1", 30);
    uniCommand1.Parameters.Add("param2", "SALES");
    uniCommand1.Parameters.Add("param3", "CHICAGO");
    
    
    Dim uniCommand1 as UniCommand
    ...
    uniCommand1.CommandText = "insert into dept (deptno, dname, loc) values (?, ?, ?)"
    uniCommand1.Parameters.Add("param1", 30)
    uniCommand1.Parameters.Add("param2", "SALES")
    uniCommand1.Parameters.Add("param3", "CHICAGO")
    
    

    Named parameters require accordance with names of UniParameter instances in the collection. Named parameters are declared using ':' or '@' prefix followed by name of the parameter. Note that names of UniParameter objects must contain '@' symbol but not ':' symbol. You can use these prefixes at any combinations to specify parameters. There are two main advantages of named parameters. First, you do not have to care about the order in which parameters are created. Second, named parameter can appear more than once in query text, but you have to create only one instance of it in Parameters collection.

    For example, a simple Update statement that requires named parameters might look like the following:

        update dept set dname = :dname, loc = :loc where deptno = @deptno
    

    To set parameters for this query you can use the next code:

    UniCommand uniCommand1;
    ...
    uniCommand1.CommandText = "update dept set dname = :dname, loc = :loc where deptno = @deptno";
    uniCommand1.Parameters.Add("@deptno", 20);
    uniCommand1.Parameters.Add("dname", "SALES");
    uniCommand1.Parameters.Add("loc", "NEW YORK");
    
    
    Dim uniCommand1 as UniCommand
    ...
    uniCommand1.CommandText = "update dept set dname = :dname, loc = :loc where deptno = @deptno"
    uniCommand1.Parameters.Add("@deptno", 20)
    uniCommand1.Parameters.Add("dname", "SALES")
    uniCommand1.Parameters.Add("loc", "NEW YORK")
    
    

    When you invoke a stored procedure you have to create collection of parameters that corresponds strictly to set of arguments for the stored procedure in quantity and types. Names of parameters do not matter unless you set UniCommand.ParameterCheck property to true for all databases except Oracle. For Oracle names of parameters are always taken into account. You retrieve value returned by a stored function through a parameter with Direction property set to ReturnValue.

    Using automatic parameters synchronization

    The behavior described above assumes that UniCommand.ParameterCheck is false (by default). By turning it on you enable automatic synchronization of query text and UniCommand.Parameters collection. In this mode all input parameters are checked for validity, new ones are added if necessary, and redundant parameters are deleted. Thus you do not have to take care about quantity of items in UniCommand.Parameters collection, you can specify only the ones you really need. The synchronization is done as follows:

    For queries that do not represent a stored procedure the synchronization takes place when:

    For stored procedures synchronization happens when:

    A separate query is executed against the server to establish the correct types of the parameters when synchronization is performed for stored procedures.

    If synchronization is already performed, subsequent calls to these methods do not result in re-synchronization, unless you had modified Parameters collection or one of the properties listed above.

    Using parameters with stored procedures in synchronization mode

    If parameters are added to the command collection in the order that is different from the function parameters order in database, it is necessary to describe the command by setting UniCommand.ParameterCheck to true to reoder parameters in a proper way.

    When UniCommand.ParameterCheck is true you can specify only those parameters you really need. Omitted parameters will be created and assigned DBNull value. You can set up required parameters in any order you like. The collection will be filled up and sorted as a result of synchronization.

    When working with stored procedures in synchronization mode you can use named parameters only. Parameter's name must match exactly name of procedure's argument. However the ReturnValue parameter needs not to have any specific name.

    In synchronization mode first call to UniCommand.Prepare or UniCommand.Execute methods leads to recreation of all argument parameters. If name of a parameter is suitable for the description of stored procedure, parameter is preserved in the collection, otherwise it is lost. If UniCommand.CommandText property and Parameters collection are unchanged all subsequent invocations of Prepare or Execute methods will not result in recreation of parameters.

    For example, consider you had a stored procedure that accepts two arguments, deptno and dname, and then changed UniCommand.CommandText to reference another stored procedure that accepts deptno and loc arguments. In this case you will have first parameter unchanged, and the second parameter recreated with value assigned to DBNull.

    Performance issues

    In general, setting UniCommand.ParameterCheck property to true leads to some performance loss.
    When UniCommand.CommandType is "Text" the synchronization is performed on client, so performance reduces very slightly.
    When UniCommand.CommandType is "StoredProcedure", Data Provider sends additional requests to server which are necessary to determine quantity, names, and other information about parameters. Thus performance mostly depends on how fast these additional round trips are performed.

    Examples

    Let's consider some examples based on dotConnect for Oracle connected to Oracle server.

    The first example demonstrates how flexible and convenient usage of parameters can be. In the example two new Sales departments are added to table Dept; then all departments with this name are rendered to console.

    First, query text is assigned to UniCommand object. When UniCommand.ParameterCheck is set to true dotConnect Universal automatically creates collection of parameters you can access to set values. Then two rows are added to table then, each referencing Sales department. Afterwards the query text is changed and again UniCommand.Parameters collection is rebuilt. This time it has only one item in it. Notice that this parameter was assigned an Int32 value before and now it holds a string. Note that the Prepare() method isn't supported by all databases, so it is only a stub in dotConnect Universal (unlike others providers where it implements native Prepare method).

    static void Main(string[] args)
    {
      UniConnection myConn = new UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora");
      myConn.Open();
      UniCommand myCommand = new UniCommand("INSERT INTO Dept VALUES (:p1, :p2, :p3)", myConn);
      myCommand.ParameterCheck = true;
      myCommand.Prepare();
      myCommand.Parameters[0].Value = 60;
      myCommand.Parameters[1].Value = "SALES";
      myCommand.Parameters[2].Value = "LA";
      myCommand.ExecuteNonQuery();
      myCommand.Parameters[0].Value = 70;
      myCommand.Parameters[2].Value = "DETROIT";
      myCommand.ExecuteNonQuery();
      myCommand.CommandText = "SELECT * FROM Dept WHERE DName=:p1";
      myCommand.Parameters[0].Value = "SALES";
      UniDataReader myReader = myCommand.ExecuteReader();
      while (myReader.Read())
      {
        Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(2));
      }
      myReader.Close();
      myConn.Close();
      Console.ReadLine();
    }
    
    
    Sub Main()
      Dim myConn As UniConnection = New UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora")
      myConn.Open()
      Dim myCommand As UniCommand = New UniCommand("INSERT INTO Dept VALUES (:p1, :p2, :p3)", myConn)
      myCommand.ParameterCheck = True
      myCommand.Prepare()
      myCommand.Parameters(0).Value = 60
      myCommand.Parameters(1).Value = "SALES"
      myCommand.Parameters(2).Value = "LA"
      myCommand.ExecuteNonQuery()
      myCommand.Parameters(0).Value = 70
      myCommand.Parameters(2).Value = "DETROIT"
      myCommand.ExecuteNonQuery()
      myCommand.CommandText = "SELECT * FROM Dept WHERE DName=:p1"
      myCommand.Parameters(0).Value = "SALES"
      Dim myReader As UniDataReader = myCommand.ExecuteReader()
      While myReader.Read()
        Console.WriteLine(myReader.GetInt32(0).ToString() + ", " _
                        + myReader.GetString(2))
      End While
      myReader.Close()
      myConn.Close()
      Console.ReadLine()
    End Sub
    
    

    The following example shows how to get a stored function to work. We will not use parameters autosynchronisation here.

    Consider you have a stored procedure that accepts job name, selects employees with that job from table Emp, gets their total salary and returns it as function result. It may be described as follows:

    CREATE FUNCTION GETTOTALSALARY (JobParam IN VARCHAR)
      RETURN NUMBER
    AS  
      TotalSalary NUMBER; 
    BEGIN
      SELECT SUM(Sal) INTO TotalSalary FROM Emp WHERE Job=JobParam GROUP BY Job;
      RETURN TotalSalary;
    END;
    

    To pass a parameter to the function and obtain a return value you can use the following sample code.

    static void CallProc()
    {
      //Prepare connection and command
      UniConnection myConn = new UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora");
      myConn.Open();
      UniCommand myCommand = new UniCommand("GETTOTALSALARY", myConn);
      myCommand.CommandType = System.Data.CommandType.StoredProcedure;
      //Prepare parameters manually
      UniParameter myInParam = myCommand.Parameters.Add("JobParam", "SALESMAN");
      UniParameter myReturParam = new UniParameter();
      myReturParam.Direction = System.Data.ParameterDirection.ReturnValue;
      myCommand.Parameters.Add(myReturParam);
      //Execute the function and render result
      myCommand.ExecuteNonQuery();
      Console.WriteLine(myReturParam.Value);
      myConn.Close();
      Console.ReadLine();
    }
    
    
    Sub CallProc()
      'Prepare(connection And Command())
      Dim myConn As UniConnection = New UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora")
      myConn.Open()
      Dim myCommand As UniCommand = New UniCommand("GETTOTALSALARY", myConn)
      myCommand.CommandType = System.Data.CommandType.StoredProcedure
      'Prepare parameters manually
      Dim myInParam As UniParameter = myCommand.Parameters.Add("JobParam", "SALESMAN")
      Dim myReturParam As UniParameter = New UniParameter()
      myReturParam.Direction = System.Data.ParameterDirection.ReturnValue
      myCommand.Parameters.Add(myReturParam)
      'Execute the function and render result
      myCommand.ExecuteNonQuery()
      Console.WriteLine(myReturParam.Value)
      myConn.Close()
      Console.ReadLine()
    End Sub
    
    

    The last example demonstrates how to call a stored procedure in autosynchronization mode.
    Consider you have a stored procedure that adds a new employee to table Emp. It determines next suitable EmpNo, pastes current date, and checks for input parameters. If they contain a reasonable value, the procedure pastes this value as well; if a parameter contains NULL value, some defaults are used. Here is how source code for this procedure may look:

    CREATE PROCEDURE ADDEMP (
      EmpName IN VARCHAR, 
      Salary IN NUMBER
    )
    AS
      e_No NUMBER;
      e_Name VARCHAR(40);
      e_Sal NUMBER;
    BEGIN
      e_Name := 'Unnamed';  --Default value
      e_Sal := 1100;        --Default value
      IF EmpName IS NOT NULL THEN e_Name := EmpName; END IF;
      IF Salary  IS NOT NULL THEN e_Sal  := Salary;  END IF;
      SELECT Max(EmpNo) INTO e_No FROM Emp;
      INSERT INTO Emp (EmpNo, EName, Sal, HireDate)
         VALUES (e_No+10, e_Name, e_Sal, SYSDATE);
    END;
    

    We will invoke this procedure and pass it single parameter - EmpName. Since ParameterCheck is true, the second parameter will be created in the moment of calling ExecuteNonQuery method. So this code will result in adding of new employee with name Roger and default salary (1100).

    Note that in autosynchronisation mode the only thing that matters is name of a parameter. You do not have to take care of creation order and there's no need to create parameters that are intended to have NULL value. Put another words, if we need to add an employee with default name but with specific salary, we can create single argument with ParameterName set to "Salary".

    static void CallProc()
    {
      //Establish connection
      UniConnection myConn = new UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora");
      myConn.Open();
      //Set up myCommand to reference stored procedure 'AddEmp'
      UniCommand myCommand = new UniCommand("AddEmp", myConn);
      myCommand.CommandType = System.Data.CommandType.StoredProcedure;
      myCommand.ParameterCheck = true;
    
      //Create input parameter and assign a value
      UniParameter myInParam1 = new UniParameter();
      myInParam1.Value = "Roger";
      myInParam1.ParameterName = "EmpName";
      myCommand.Parameters.Add(myInParam1);
      myInParam1.Direction = System.Data.ParameterDirection.Input;
    
      //Execute the procedure.
      myCommand.ExecuteNonQuery();
      Console.WriteLine("Done");
      myConn.Close();
    }
    
    
    Sub CallProc()
      'Establish connection
      Dim myConn As UniConnection = New UniConnection("Provider=Oracle;User Id=Scott;Password=tiger;Data Source=Ora")
      myConn.Open()
      'Set up myCommand to reference stored procedure 'AddEmp'
      Dim myCommand As UniCommand = New UniCommand("AddEmp", myConn)
      myCommand.CommandType = System.Data.CommandType.StoredProcedure
      myCommand.ParameterCheck = True
    
      'Create input parameter and assign a value
      Dim myInParam As UniParameter = New UniParameter
      myInParam.ParameterName = "EmpName"
      myInParam.Value = "Roger"
      myCommand.Parameters.Add(myInParam)
      myInParam.Direction = System.Data.ParameterDirection.Input
    
      'Execute the procedure
      myCommand.ExecuteNonQuery()
      Console.WriteLine("Done.")
      myConn.Close()
    End Sub
    
    

    See Also

    UniParameter Class  | Devart.Data.Universal Namespace