簡體   English   中英

如何在UWP的sqlite-net-pcl中使用REGEXP

[英]How to use REGEXP in `sqlite-net-pcl` in UWP

我有一個可與Sqlite數據庫一起使用的UWP項目。 我在引用中添加了sqlite-net-pcl 我想在select查詢中使用REGEXP ,但它no such function: REGEXP 我搜索了錯誤,但結果與此處未定義的SQLiteFunction有關。 我該怎么辦?

引用LIKE,GLOB,REGEXP和MATCH運算符

REGEXP運算符是regexp()用戶函數的一種特殊語法。 默認情況下,沒有定義regexp()用戶函數,因此使用REGEXP運算符通常會導致錯誤消息。 如果在運行時添加了應用程序定義的名為“ regexp”的SQL函數 ,則將實現“ X REGEXP Y”運算符,作為對“ regexp(Y,X)”的調用。

因此,要使用REGEXP,我們需要能夠創建用戶定義的函數。 SQLiteFunction是旨在輕松在System.Data.SQLite中處理用戶定義的函數的類。 但是System.Data.SQLite是SQLite的ADO.NET提供程序,不能在UWP應用程序中使用。

SQLite-net PCL中 ,沒有這種方法。 但是,SQLite-net PCL在下面使用SQLitePCL.raw ,它是用於SQLite的C API的非常薄的C#包裝器,並提供對SQLite的低級(原始)訪問。 使用SQLitePCL.raw,我們可以創建用戶定義的函數,就像@Maryam的答案一樣。

最后,我從nuget安裝了sqlite-net-pclnuget不是ReferenceManger的Universal windows extensions中的一個。

nuget中的sqlite-net-pcl軟件包具有sqlite3_create_function方法。

SQLiteConnection con = new SQLiteConnection(@"myDB.db");
SQLitePCL.raw.sqlite3_create_function(con.Handle, "REGEXP", 2, null, MatchRegex);

private void MatchRegex(sqlite3_context ctx, object user_data, sqlite3_value[] args)
    {
        bool isMatched = System.Text.RegularExpressions.Regex.IsMatch(SQLitePCL.raw.sqlite3_value_text(args[1]), SQLitePCL.raw.sqlite3_value_text(args[0]),RegexOptions.IgnoreCase);
        if (isMatched)
            SQLitePCL.raw.sqlite3_result_int(ctx, 1);
        else
            SQLitePCL.raw.sqlite3_result_int(ctx, 0);
    }

這很好:)

如果您可以使用SQLite PCL Pretty之類的工具,則可以執行以下操作(可能無法與其他PCL一起使用):

using System;
using SQLitePCL.pretty;
using System.Text.RegularExpressions;

namespace TestSqlite
{ 
    class Program
    {
        static void Main(string[] args)
        {
            Func<ISQLiteValue, ISQLiteValue, ISQLiteValue> regexFunc =
                        (ISQLiteValue val, ISQLiteValue regexStr) =>
                        {
                            if (Regex.IsMatch(Convert.ToString(val), Convert.ToString(regexStr)))
                                return true.ToSQLiteValue();
                            return false.ToSQLiteValue();
                        };
            SQLitePCL.Batteries.Init();
            SQLiteDatabaseConnection _dbcon = SQLiteDatabaseConnectionBuilder
                        .InMemory
                        .WithScalarFunc("REGEXP", regexFunc)
                        .Build();
            string sql = "CREATE TABLE foo (a int, b text);";
            _dbcon.ExecuteAll(sql);
            _dbcon.ExecuteAll(@"INSERT INTO foo VALUES (1, 'this is me');
                                INSERT INTO foo VALUES (2, 'that is me');
                                INSERT INTO foo VALUES (3, 'he is me');");
            sql = "SELECT * FROM foo where '\\w{4} is me' REGEXP b;";
            foreach (var row in _dbcon.Query(sql)) { Console.WriteLine(row[1].ToString()); }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM