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