首页 > 解决方案 > C#sqlite如何从执行的sqlite命令行打印受影响的行.read

问题描述

我有一个名为 query.sql 的文件,其中包含一个事务,我想使用我的 C# 代码中的 sqlite 命令行执行该文件。它工作正常,但我无法从命令行输出中获取受影响的行。我想获取受影响的行并使用 MessageBox 显示它。

我的 C# 代码使用 Process :

ProcessStartInfo startinfo = new ProcessStartInfo("sqlite3.exe");
startinfo.Arguments = string.Format("\"{0}\" \".read '{1}'\"",DatabasePath, Path.Combine(Path.GetTempPath(), "query.sql"));
//startinfo.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(startinfo);

从命令行查看:

sqlite3.exe "C:\Users\me\AppData\Local\app\database.db" ".read 'C:\Users\me\AppData\Local\Temp\query.sql'"

我的 sql 文件示例:

我执行了命令并且数据库发生了变化,但我无法捕获受影响的行。如何从该进程中捕获受影响的行?

标签: c#sqlite

解决方案


首先,您需要添加Select Changes();到 SQL 的末尾。

https://www.sqlite.org/lang_corefunc.html#changes

然后,您需要设置流程以将输出重定向到您的应用程序。

startinfo.UseShellExecute = false;
startinfo.RedirectStandardOutput = true;
var proc = Process.Start(startinfo);
while (!proc.StandardOutput.EndOfStream)
{
    string output = proc.StandardOutput.ReadLine();
    Console.WriteLine(output);
}

https://stackoverflow.com/a/4291965/7182460

虽然上述方法应该有效,但还有一种更简单的方法。我不确定您使用命令行的原因是什么。您可能想看看使用 ORM。

https://github.com/praeclarum/sqlite-net


推荐阅读