在C#中,使用OleDbParameter對象來添加參數到OleDbCommand對象中。可以通過以下步驟來使用OleDbParameter:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers WHERE Country = ?", connection);
OleDbParameter parameter = new OleDbParameter("CountryParam", OleDbType.VarChar);
parameter.Value = "USA";
cmd.Parameters.Add(parameter);
OleDbDataReader reader = cmd.ExecuteReader();
完整的示例代碼如下所示:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers WHERE Country = ?", connection))
{
OleDbParameter parameter = new OleDbParameter("CountryParam", OleDbType.VarChar);
parameter.Value = "USA";
cmd.Parameters.Add(parameter);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// 處理查詢結果
}
}
}
}
需要注意的是,參數名稱在SQL語句中使用?
占位符,然后通過添加OleDbParameter對象來指定參數的值。在執行查詢之前,必須先打開OleDbConnection對象。