8.4 使用預處理語句

X DevAPI 藉由針對每個重複執行的 CRUD 語句使用伺服器端預處理語句,來提高效能。這在內部發生,只要重複使用相同的操作物件,應用程式就不需要執行任何額外動作來利用此功能。

當語句第二次執行時,只有資料值或精簡執行結果的值有所變更(例如,不同的 offset()limit() 值),伺服器會準備該語句以供後續執行,這樣在再次執行時就不需要重新剖析該語句。預處理語句重新執行的新值會透過參數繫結提供。當語句透過串聯到其上的方法(例如,sort()limit()offset())來修改以精簡結果時,該語句會重新準備。以下虛擬程式碼和它們的註解示範此功能

var f = coll.find("field = :field");
f.bind("field", 1).execute(); // Normal execution
f.bind("field", 2).execute(); // Same statement executed with a different parameter value triggers statement preparation
f.bind("field", 3).execute(); // Prepared statement executed with a new value
f.bind("field", 3).limit(10).execute(); // Statement reprepared as it is modified with limit()
f.bind("field", 4).limit(20).execute(); // Reprepared statement executed with new parameters

請注意,若要利用此功能,必須在語句的重複執行中重複使用相同的操作物件。請看此範例

for (i=0; i<100; ++i) {
    coll.find("field = :field").bind("field", i).execute();
}

此迴圈無法利用預處理語句功能,因為 coll.find() 的操作物件會在 for 迴圈的每次迭代中重新建立。現在,請看此範例

var f = coll.find("field = :field");
 
for (i=0; i<100; ++i) {
    f.bind("field", i).execute();
}

重複的語句會準備一次,然後重複使用,因為 coll.find() 的相同操作會針對 for 迴圈的每次迭代重新執行。

預處理語句是 Session 的一部分。當 Client 重設 Session(例如,使用 Mysqlx.Session.Reset)時,預處理語句會被捨棄。