2010-05-25 67 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