OleDb 参数数组格式

OleDb Parameters Array Format

嗨,在 OleDB 文档中(链接如下)他们在函数中有一个名为 OleDbParameter[] parameters 的参数,然后循环遍历该数组以将参数插入 SQL.

我在文档中找不到您应该如何格式化该数组?

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

Microsoft Example 中的代码错误且不可编译。我已经发送了关于它的反馈。这里有一个更正确的版本,带有关于更改内容的注释。

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);
}

现在要调用这个函数你有

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);