SQLite 內部是按二進制排序, 可以支持 ANSI; FrieDAC 通過 TFDSQLiteCollation 支持了 Unicode 排序, 並可通過其 OnCompare 事件自定義排序.
下面的例子, 測試了這兩種排序的不同.
可把下面代碼直接貼在空白窗體上, 以快速完成窗體設計:
代碼:
procedure TForm1.FormCreate(Sender: TObject);
var
i: Integer;
LCode: Integer;
begin
{給 FDSQLiteCollation1 設定參數}
FDSQLiteCollation1.DriverLink := FDPhysSQLiteDriverLink1;
// FDSQLiteCollation1.CollationKind := scCompareString; //這是默認值(Unicode 不區分大小寫, 在 Win 下是調用 WinAPI.CompareString); 使用其他選項需要自定義排序規則
FDSQLiteCollation1.LocaleName := 'zh-CN';
FDSQLiteCollation1.Flags := [sfIgnoreCase];
FDSQLiteCollation1.CollationName := 'MyCollation'; //下面所有的調用全要依賴這個名稱
FDSQLiteCollation1.Active := True;
FDConnection1.Params.Add('DriverID=SQLite');
// FDConnection1.Params.Add('OpenMode=CreateUTF8'); //這是默認值, 可選 CreateUTF16(Unicode)
{建立測試表, 三個字段 str(漢字), code(漢字對應的 Unicode 值), id(添加順序)}
FDConnection1.ExecSQL('CREATE TABLE MyTable(str string(10), code integer, id integer)');
// FDConnection1.ExecSQL('CREATE TABLE MyTable(str string(10) COLLATE MyCollation, code integer, id integer)'); //用在表設計時
{添加測試數據數據}
for i := 0 to 99 do
begin
LCode := Random($9FA5-$4E00);
FDConnection1.ExecSQL('INSERT INTO MyTable(str, code, id) VALUES(:1, :2, :3)', [WideChar($4E00 + LCode), LCode, i+1]);
end;
FDQuery1.Open('SELECT * FROM MyTable'); //無排序
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FDQuery1.Open('SELECT * FROM MyTable ORDER BY str'); //SQLite 內置排序
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
FDQuery1.Open('SELECT * FROM MyTable ORDER BY str COLLATE MyCollation'); //FireDAC 默認排序
end;
測試效果圖:
