2010-05-25 69 views
2

我有一个C#应用程序,我试图检查我的sqlite数据库,如果文件名已经存在于FileName列,如果它不存在,执行一些代码..这是我我在一起工作。澄清 - 此代码does not工作..它说我不能将insertCommand.ExecuteNonQuery转换为字符串。我需要查询表,如果文件名不存在,然后继续。C#IF语句对SQLite查询结果

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 
} 

编辑:让斜线不吃引号

+1

所以......有什么问题吗? – Jay 2010-05-25 18:27:37

+0

对不起,这是个糟糕的描述。我更新上面..更有意义? – 2010-05-25 18:32:42

回答

2

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

SELECT COUNT(*)FROM导入行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. 
    } 
} 
+0

“提供给命令的参数不足”是我得到的int count = Convert.ToInt32等错误。缺少一些东西? – 2010-05-25 18:53:42

+0

是的,你缺少参数。 “@FileName”是查询的参数。出于这个原因,它被称为参数化查询。例如,查看http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/。 – Patko 2010-05-25 19:06:33

+0

非常好!它工作,我唯一的问题,我以前发生过这种情况,是当我添加额外的参数,它抛出我的数据库中的列...所有的数据被移动1列。为什么是这样? – 2010-05-25 19:20:18

0

ExecuteNonQuery对于非查询路径增值空间。如果您想查询数据时,使用ExecuteReader

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

hmm。好的,所以这是返回表中的列号?我可以说,字符串myVar = myReader.GetString(0);然后将它用于if语句? - 猜我不知道如果在什么地方 – 2010-05-25 18:38:46

+0

@jake:我没有任何'如果',我不知道你在说什么。 – 2010-05-25 19:33:21