【问题标题】:Why does this query string work in Access but not C#?为什么此查询字符串在 Access 中有效,但在 C# 中无效?
【发布时间】:2026-02-07 21:40:01
【问题描述】:

我有这段代码:

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 行。

【问题讨论】:

    标签: c# sql ms-access


    【解决方案1】:

    我假设您在这里的行为声明:

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

    表示“TextBox 文本被替换为‘不匹配’”。对吗?

    这会返回很多行。

    嗯,这就解释了。看看你的情况:

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

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

    你可能想要:

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

    【讨论】:

    • 是的,我在发布我的问题后立即发现了这一点。谢谢!
    【解决方案2】:

    你应该这样做:

    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";
    }
    

    【讨论】:

      最近更新 更多