Hi在OleDB文档中(链接如下(,它们在函数中有一个名为OleDbParameter[] parameters
的参数,然后循环遍历该数组,将参数插入SQL。
我在文档中找不到应该如何格式化该数组?
文档:https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?view=dotnet-plat-ext-3.1
Microsoft示例中的代码是错误的,不可编译。我已经发送了关于它的反馈。这里有一个更正确的版本,带有关于更改内容的注释。
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);