C# 如何在UWP中的`sqlite net pcl`中使用REGEXP
我有一个使用Sqlite数据库的UWP项目。我将sqlite net pcl添加到我的引用中。 我想在select查询中使用REGEXP,但它没有提供这样的函数:REGEXP。 我搜索了错误,但结果是关于SQLiteFunction的,这里没有定义。 我该怎么办?参考: REGEXP运算符是REGEXP用户函数的特殊语法。默认情况下未定义任何regexp用户函数,因此使用regexp运算符通常会导致错误消息。如果在运行时添加了命名的regexp,那么X regexp Y操作符将作为对regexpY,X的调用来实现 因此,要使用REGEXP,我们需要能够创建用户定义的函数。并且是设计用于在中轻松处理用户定义函数的类。但是System.Data.SQLite是SQLite的ADO.NET提供程序,不能在UWP应用程序中使用C# 如何在UWP中的`sqlite net pcl`中使用REGEXP,c#,sqlite,uwp,sqlite-net,C#,Sqlite,Uwp,Sqlite Net,我有一个使用Sqlite数据库的UWP项目。我将sqlite net pcl添加到我的引用中。 我想在select查询中使用REGEXP,但它没有提供这样的函数:REGEXP。 我搜索了错误,但结果是关于SQLiteFunction的,这里没有定义。 我该怎么办?参考: REGEXP运算符是REGEXP用户函数的特殊语法。默认情况下未定义任何regexp用户函数,因此使用regexp运算符通常会导致错误消息。如果在运行时添加了命名的regexp,那么X regexp Y操作符将作为对regexp
在中国,没有这样的方法。然而,SQLite net PCL使用Underflow,它是围绕SQLite的C API的一个非常薄的C包装器,并提供对SQLite的低级原始访问。使用SQLitePCL.raw,我们可以创建用户定义的函数,如@Maryam的答案所示。如果您可以使用类似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()); }
}
}
}
最后,我从nuget安装了sqlite net pcl,而不是ReferenceManger中的Universal windows extensions中的那个
nuget中的sqlite net pcl包具有sqlite3_create_函数方法
这很好:哇!没有注意到SQLite net PCL是基于SQLitePCL.raw构建的。sqlite3_create_函数方法实际上不是SQLite net PCL的方法,而是SQLitePCL.raw中的方法。无论如何,这是解决这个问题的好办法;我所缺少的只是对utf8\u to\u字符串的调用,如SQLitePCL.raw.sqlite3\u value\u text args[0].utf8\u to\u字符串中的调用
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);
}