UniDAC 使用 Sqlite 时的中文排序(原创)
使用 RegisterWideCollation 注册新的排序规则即可,注册后的排序规则可以在对中文字段排序时使用:
procedure TForm1.Button1Click(Sender: TObject);
begin
// UniDac 必须携带 sqlite3.dll 文件,32位编译器编译的程序只能使用 32 位的 sqlite3.dll
// sqlite3.dll 可更名为自己喜欢的文件名
UniConnection1.SpecificOptions.Values['ClientLibrary'] := '.\sqlite3.dll';
// 在 UniConnection 的选项中,要把 text 类型列映射为WideString类型
UniConnection1.Open;
// 注册新的排序规则 'py',TLiteUtils 不用声明,可以直接引用。注意:只有在连接后才能注册 Collation
TLiteUtils.RegisterWideCollation(UniConnection1, 'py', WideCompareStr); // WideCompareStr 是 SysUtils 单元里的函数
// 旧方法,配合自定义比较函数注册排序规则,下面必须用 RegisterCollation,使用 RegisterWideCollation 反而不行
// TLiteUtils.RegisterCollation(UniConnection1, 'py', CompStr); // 详见下面的 CompStr 函数
// 指定 Table 按 name 列排序,默认 Collation 为 py
UniTable1.OrderFields := 'name collate py';
UniTable1.Open;
// 指定 Query 按 name 列排序,默认 Collation 为 py
uniquery1.Close;
uniquery1.SQL.Clear;
uniquery1.SQL.Add('select * from t1 order by name collate py;');
uniquery1.Prepare;
uniquery1.Open;
end;
旧代码,需要创建自定义排序函数,配合 RegisterCollation 使用
// 形参前面的 const 非常重要,如果缺少,会提示 “Parameter lists differ” 错误
function CompStr(const Str1, Str2: string): Integer;
begin
Result := WideCompareStr(Str1, Str2);
{ // 以下代码对 “李白” 和 “垚哥” 两词组排序有问题,使用 WideCompareStr 则完全正确
if str1 > str2 then
result := 1
else if str1 < str2 then
result := -1
else
result := 0;
}
end;


浙公网安备 33010602011771号