为什么这个查询字符串在Access中工作但不在C#中工作?

时间:2013-03-11 18:11:36

标签: c# sql ms-access

我有这段代码:

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)

因为可能会返回多于一行。

2 个答案:

答案 0 :(得分:3)

我假设你的行为陈述在这里:

  

当我运行它时,它不会返回任何结果。

表示“TextBox文字被替换为'不匹配'”。是吗?

  

这将返回许多行。

那就解释了。看看你的情况:

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

你声称在每种情况下都有没有匹配,除非只有一个匹配。

你可能想要:

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

答案 1 :(得分: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";
}
相关问题