[PHP] GetUpdateSQL
最近因為維護的案子是用 PHP 寫的,在維護上時發現到 GetUpdateSQL 這個語法,覺得還蠻特別的,過去在寫 C# 好像還沒用到這樣的寫法,先來看一下這個 網站 上面的解釋:
Generate SQL to update a table given a recordset $rs, and the modified fields of the array $arrFields (which must be an associative array holding the column names and the new values) are compared with the current recordset. If $forceUpdate is true, then we also generate the SQL even if $arrFields is identical to $rs->fields. Requires the recordset to be associative. $magicq is used to indicate whether magic quotes are enabled (see qstr()).
基本上就是我們存資料庫取得資料後,都會放在 recordset 裡面,然後我們把 recordset 的資料改丟到陣列裡面,當我要修改的時候,如果要在寫 UPDATE TABLE SET ... 那可多麻煩~
所以使用這種方法後,程式碼大概如下:
Generate SQL to update a table given a recordset $rs, and the modified fields of the array $arrFields (which must be an associative array holding the column names and the new values) are compared with the current recordset. If $forceUpdate is true, then we also generate the SQL even if $arrFields is identical to $rs->fields. Requires the recordset to be associative. $magicq is used to indicate whether magic quotes are enabled (see qstr()).
基本上就是我們存資料庫取得資料後,都會放在 recordset 裡面,然後我們把 recordset 的資料改丟到陣列裡面,當我要修改的時候,如果要在寫 UPDATE TABLE SET ... 那可多麻煩~
所以使用這種方法後,程式碼大概如下:
- $sql = "Select * FROM Table Where id = 1";
- $rs = $conn->Execute($sql);
- $record = array();
- $record["RecordA"] = "DataA";
- $record["RecordB"] = "DataB";
- 這樣就會產生一個 UPDATE 的 SQL 語法把資料做更新
- $updateSQL = $conn->GetUpdateSQL($rs, $record, false ,true);
- $conn->Execute($updateSQL);
- $conn->Close();
使用這樣的方法就不用自己在拚 SQL 語法了,我覺得還蠻不錯的,不知道 .NET 或是 JAVA 裡面有沒有這個功能呢?