针对 SQLite 查询结果的 C# IF 语句

标签 c# sqlite

我有一个 C# 应用程序,我正在尝试检查我的 sqlite 数据库,如果文件名已存在于 FileName 列中,如果它不存在,则执行一些代码。这是我正在使用的。澄清 - 此代码不起作用..它说我无法将 insertCommand.ExecuteNonQuery 转换为字符串。我需要查询表,如果文件名不存在,则继续。

string[] files = Directory.GetFiles(@"C:\Documents and Settings\js91162\Desktop ",
        "R303717*.txt*", SearchOption.AllDirectories);
foreach (string file in files)
{
    string FileNameExt1 = Path.GetFileName(file);

    insertCommand.CommandText = @" 
            SELECT * FROM Import WHERE FileName == FileNameExt1;";
}
string contYes = insertCommand.ExecuteNonQuery();

if (string.IsNullOrEmpty(contYes))
{
    //more code
}

编辑:在路径中添加空格,这样斜杠就不会吃掉引号

最佳答案

如果你想检查是否有一个文件名的行,那么你也可以使用 ExecuteScalar

SELECT COUNT(*) FROM Import WHERE FileName = @FileName

当然你还必须为命令设置参数。然后你可以做

int count = Convert.ToInt32(insertCommand.ExecuteScalar());
if (count == 0)
{
  // code...
}

编辑:带参数的整个东西看起来像这样:

selectCommand.CommandText = "SELECT COUNT(*) FROM Import Where FileName = @FileName";
selectCommand.Parameters.Add("@FileName", SqlDbType.NVarChar); // Use appropriate db type here
insertCommand.CommandText = "INSERT INTO Import (FileName, ...) VALUES (@FileName, ...");
insertCommand.Parameters.Add("@FileName", SqlDbType.NVarChar);
// Add your other parameters here.
// ...
foreach (string file in files) 
{ 
  var fileName = Path.GetFileName(file);
  selectCommand.Parameters[0].Value = Path.GetFileName(fileName);
  int count = Convert.ToInt32(selectCommand.ExecuteScalar());
  if (count == 0)
  {
    // File does not exist in db, add it.
    insertCommand.Parameters[0].Value = fileName;
    // Init your other parameters here.
    // ...

    insertCommand.ExecuteNonQuery(); // This executes the insert statement.
  }
}

关于针对 SQLite 查询结果的 C# IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2907359/

相关文章:

c# - Umbraco 工作提要 rss

c# - 如何删除 XMLDocument 中的特定属性?

c# - 如何在类中使用自定义类和List <>进行foreach循环

c# - 是否有执行 .SelectMany(x => x) 的 Linq 方法?

python - 将文字百分号传递给 QuerySet.extra()

python - 在 sqlite3.connect() 中使用用户输入的变量是否存在安全风险?

python - 将 CSV 文件写入 PDF 文档

c# - 从左连接中选择时出现 NullReferenceException

android - "SQLite Error: No Such Column "即使它是一个值

mysql - SQLite 和 MySQL 中使用 Unicode 代码点的 SQL 查询