繁体   English   中英

通过C#对Access数据库进行的LIKE查询始终返回COUNT(*)为0

[英]LIKE query on an Access database via C# always returns COUNT(*) of 0

请查看以下代码:

using (OleDbConnection openCon = new OleDbConnection(ConfigurationManager.AppSettings["AccessConnectioString"]))
{
                openCon.Open();
                string tc = string.Empty;
                string ttc = string.Empty;
                if (!string.IsNullOrEmpty(QSetId))
                {
                    tc = "select count(*) as [Count] from ABC where QSetId = @qSetId and TText like 'RT*'";
                }
                else
                {
                    tc = "select count(*) as [Count] from PQR where TText like 'RT*'";
                }
                using (OleDbCommand qtc= new OleDbCommand(tc))
                {
                    qtc.Connection = openCon;
                    if (!string.IsNullOrEmpty(QSetId))
                        qtc.Parameters.Add("@qSetId", OleDbType.VarChar).Value = QSetId;
                    OleDbDataReader dr1 = qtc.ExecuteReader();
                    while (dr1.Read())
                    {
                        ttCnt = (int)dr1["Count"];
                    }
                }

                openCon.Close();
}

我总是得到计数为0而不是一些整数值。 调试时,我接受查询并在MS ACCESS 2013中执行,它为我提供了正确的结果。 我没有得到什么问题。

在Access本身中运行的查询与从外部应用程序运行的查询之间,LIKE通配符之间的差异使您大跌眼镜。

从Access本身运行查询时,需要使用星号作为通配符: LIKE 'RT*'

从外部应用程序(例如C#应用程序)运行查询时,需要使用百分号作为通配符: LIKE 'RT%'

尝试ExecuteScalar()方法

替换为:

 OleDbDataReader dr1 = qtc.ExecuteReader();
 while (dr1.Read())
 {
    ttCnt = (int)dr1["Count"];
 }

有了这个:

 ttCnt = Convert.ToInt32(qtc.ExecuteScalar());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM