Search code examples
c#oledboledbparameter

OleDb Parameters Array Format


Hi in the OleDB documentation (linked below) they have a parameter called OleDbParameter[] parametersin a functions, a loop then iterates over that array to insert the parameters into the SQL.

I can't find in the documentation how you are supposed to format that array?

Docs: https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?view=dotnet-plat-ext-3.1


Solution

  • The code in the Microsoft Example is wrong and not compilable. I have already sent a feedback about it. Here a more correct version with annotations about what to change.

    public void CreateMyOleDbCommand(OleDbConnection connection,
                      string queryString, OleDbParameter[] parameters)
    {
        OleDbCommand command = new OleDbCommand(queryString, connection);
    
        // This destroys the commandtext set by querystring in the constructor.
        // command.CommandText =
        //    "SELECT CustomerID, CompanyName FROM Customers WHERE Country = ? AND City = ?";
    
        // This cannot work, you can't add an array with Add but only one element
        // command.Parameters.Add(parameters);
        command.Parameters.AddRange(parameters);
    
        // After AddRange this loop is pointless and creates possible errors with
        // too many parameters added to the collection
        // for (int j=0; j<parameters.Length; j++)
        //{
        //    command.Parameters.Add(parameters[j]) ;
        //}
    
        string message = "";
        for (int i = 0; i < command.Parameters.Count; i++)
        {
            message += command.Parameters[i].ToString() + "\n";
        }
        Console.WriteLine(message);
    }
    

    Now to call this function you have

    string cmdText = @"SELECT CustomerID, CompanyName 
                       FROM Customers 
                       WHERE Country = ? AND City = ?";
    OleDbParameter[] parameters = new OleDbParameter[]
    {
        new OleDbParameter{ ParameterName = "?",OleDbType = OleDbType.VarWChar, Value = "UK" },
        new OleDbParameter{ ParameterName = "?",OleDbType = OleDbType.VarWChar, Value = "London"},
    };
    CreateMyOleDbCommand(myConnection, cmdText, parameters);