2013-03-11 72 views
0

我有這段代碼:爲什麼這個查詢字符串在Access而不是C#中工作?

conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\\myDB.accdb"); 
conn.Open(); 

sql = string.Format("SELECT Version FROM tblVersions where [FUL Flag] = 'Y'"); 
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); 
DataSet ds = new DataSet(); 

da.Fill(ds); 
dt = ds.Tables[0]; 

if (ds.Tables[0].Rows.Count == 1) 
{ 
    tV.Text = dt.Rows[0][0].ToString(); //only looking for the first result 
} 
else 
{ 
    tV.Text = "no match"; 
} 

當我運行它,它不返回任何結果。但是,如果我複製SELECT語句並將其右側粘貼到Access中的查詢窗口中,它確實會查找結果。這裏是我粘貼到Access:

SELECT Version FROM tblVersions where [FUL Flag] = 'Y' 

這會返回很多行。

我錯過了某處的區別嗎?謝謝!

編輯:找到了解決辦法。我應該尋找

(ds.Tables[0].Rows.Count > 0) 

,而不是

(ds.Tables[0].Rows.Count == 1) 

由於超過1行可退還。

回答

3

我假設你的行爲在這裏聲明:

當我運行它,它不返回任何結果。

表示「該TextBox文本被替換爲'不匹配'」。是對的嗎?

這會返回很多行。

那就解釋一下吧。看看你的條件:

if (ds.Tables[0].Rows.Count == 1) 

你聲稱有在任何情況下不比賽,除非有確切一個比賽。

你可能想:

if (ds.Tables[0].Rows.Count > 0) 
+0

是啊,我抓住了這張貼我的問題之後。謝謝! – 2013-03-11 18:14:01

1

你應該這樣做:

ds.Tables[0].Rows.Count > 0 instead of ==1 

完整的示例:

if (ds.Tables[0].Rows.Count > 0) 
{ 
    tV.Text = dt.Rows[0][0].ToString(); //only looking for the first result 
} 
else 
{ 
    tV.Text = "no match"; 
} 
相關問題