【问题标题】:C# IF statement against SQLite query result针对 SQLite 查询结果的 C# IF 语句
【发布时间】:2010-05-26 04:20:26
【问题描述】:

我有一个 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
}

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

【问题讨论】:

  • 抱歉,描述不佳。我在上面更新了.. 更有意义?

标签: c# sqlite


【解决方案1】:

如果您想检查是否存在带有某个文件名的行,那么您也可以将 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.
  }
}

【讨论】:

  • “提供给命令的参数不足”是我得到的 int count = Convert.ToInt32 等错误。缺少什么?
  • 是的,您缺少参数。 “@FileName”是查询的参数。因此,它被称为参数化查询。以aspnet101.com/2007/03/parameterized-queries-in-asp-net 为例。
  • 非常好!它起作用了,我唯一的问题,我以前也遇到过这种情况,就是当我添加那个额外的参数时,它会丢弃我数据库中的列......所有数据都移动了 1 列。这是为什么呢?
  • 如果丢掉列是什么意思? Select 语句不会修改您的数据库。
  • 好的,所以现在我只剩下一个有效的 if 语句,但是,如果文件与数据库中的文件相同,它就不会运行。这就是我想要的。但是,如果添加了一个新文件,那么它会重新添加所有文件,加上新文件。我怎样才能让它只添加新文件??
【解决方案2】:

ExecuteNonQuery 用于非查询。如果要查询数据,使用ExecuteReader

SqlDataReader myReader = insertCommand.ExecuteReader();
while(myReader.Read()) 
{
    Console.WriteLine(myReader.GetString(0)); //0 is the column-number
}

【讨论】:

  • 嗯。好的,所以这是返回表中的列号?我可以说,字符串 myVar = myReader.GetString(0);然后将其用于 if 语句? - 猜我对 if 的来源感到困惑
  • @jake:我没有if,我不知道你在说什么。
猜你喜欢
  • 2015-06-24
  • 1970-01-01
  • 2013-10-15
  • 2021-04-07
  • 2012-04-14
  • 1970-01-01
  • 2022-08-18
  • 2012-02-03
  • 1970-01-01
相关资源
最近更新 更多