2010-01-26 58 views
1

我有一個文本框和搜索按鈕我試圖尋找的文件名在數據庫表和數據表顯示它們...搜索數據庫表,並把它放在一個DataTable

private void GetSearchResults(string machineID, string searchFileName) 
{ 
    DataTable dt = new DataTable(); 
    SqlConnection connection = new SqlConnection(); 
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString; 
    connection.Open(); 
    SqlCommand sqlCmd = new SqlCommand("SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like '%@searchFileName%' AND [email protected]", connection); 
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); 

    sqlCmd.Parameters.AddWithValue("@machineID", machineID); 

    sqlCmd.Parameters.AddWithValue("@searchFileName", searchFileName); 

    sqlDa.Fill(dt); 
} 

一切做工精細除了searchFileName沒有在查詢工作......

我試圖把只是一個值來檢查像

SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like '%b%' AND [email protected] 

和我得到的文件中的值...

有什麼建議.. ??

+0

你試過在調試器步進通過?當函數被調用時searchFileName的值是多少? – 2010-01-26 19:19:50

+1

您還需要在'SqlConnection','SqlCommand'和'SqlDataAdapter'實例周圍使用''塊。 – 2010-01-26 19:30:19

回答

3

你有你的變量一個字符串,它講的是數據庫來搜索文本字符串內「@searchFileName」。要使用該變量的值,試試這個

'%' + @searchFileName + '%' 
1

這裏有您需要什麼:

private void GetSearchResults(string machineID, string searchFileName) 
{ 
    DataTable dt = new DataTable(); 
    SqlConnection connection = new SqlConnection(); 
    connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString; 
    connection.Open(); 
    SqlCommand sqlCmd = new SqlCommand("SELECT FileID, BuFileName FROM BackedUpFiles WHERE BuFileName Like @searchFileName AND [email protected]", connection); 
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); 

    sqlCmd.Parameters.AddWithValue("@machineID", machineID); 

    sqlCmd.Parameters.AddWithValue("@searchFileName", String.Format("%{0}%",searchFileName); 

    sqlDa.Fill(dt); 
} 

我以前碰到這個。出於某種原因,它不知道如何解析出引用中的參數。我想它認爲這是一個文字。

+0

如果您的dbms每次都將其識別爲變量,您將如何在數據庫中搜索「@」? – 2010-01-26 19:30:08

1

試試這個在您選擇

SELECT FileID, BuFileName FROM BackedUpFiles where REGEXP_LIKE(upper(BuFileName),UPPER(@searchFileName)) AND [email protected]; 
相關問題