Access 雖無 SQL Server 完善的預存程序支援,但可用「查詢」儲存參數化 SQL,配合 OleDbCommand 以 CommandType.StoredProcedure 呼叫,達到類似效果。本文示範刪除人員資料的完整流程。
public class Person
{
private const string SP_DELETE = "[asp_Person_Delete]"; // Access 查詢名需方括號
private const string PARAM_ID = "@PersonID";
private OleDbParameter[] GetDeleteParams(int id)
{
return new OleDbParameter[] {
new OleDbParameter(PARAM_ID, OleDbType.Integer) { Value = id }
};
}
public bool Delete(int personID)
{
OleDbParameter[] pars = GetDeleteParams(personID);
try
{
int affected = Utility.Tools.CreateOleDbCommandExecuteNonQuery(SP_DELETE, pars);
return affected > 0;
}
catch { return false; }
}
}
PARAMETERS [PersonID] Short;
DELETE * FROM PersonInfo WHERE [PersonInfo].[PersonID] = [PersonID];
asp_Person_Delete(方括號會自動加上)PARAMETERS [ID] Short, [Name] Text(50), [BirthDate] DateTime;
INSERT INTO Table1 (ID, Name, BirthDate) VALUES ([ID], [Name], [BirthDate]);
public static int CreateOleDbCommandExecuteNonQuery(string spName, OleDbParameter[] parameters)
{
using (OleDbConnection conn = new OleDbConnection(connString))
using (OleDbCommand cmd = new OleDbCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parameters != null) cmd.Parameters.AddRange(parameters);
conn.Open();
return cmd.ExecuteNonQuery();
}
}
[ ] 包圍(如 [asp_Person_Delete])。PARAMETERS 宣告一致(含 @ 前綴)。