简体   繁体   English

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

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

Please look into following code: 请查看以下代码:

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();
}

I am always getting count as 0 instead of some integer value. 我总是得到计数为0而不是一些整数值。 While debugging I take the query and execute in MS ACCESS 2013, it gives me correct result. 调试时,我接受查询并在MS ACCESS 2013中执行,它为我提供了正确的结果。 I am not getting what is the issue. 我没有得到什么问题。

You are getting tripped up by the difference in LIKE wildcard characters between queries run in Access itself and queries run from an external application. 在Access本身中运行的查询与从外部应用程序运行的查询之间,LIKE通配符之间的差异使您大跌眼镜。

When running a query from within Access itself you need to use the asterisk as the wildcard character: LIKE 'RT*' . 从Access本身运行查询时,需要使用星号作为通配符: LIKE 'RT*'

When running a query from an external application (like your C# app) you need to use the percent sign as the wildcard character: LIKE 'RT%' . 从外部应用程序(例如C#应用程序)运行查询时,需要使用百分号作为通配符: LIKE 'RT%'

Try ExecuteScalar() method 尝试ExecuteScalar()方法

Replace This: 替换为:

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

With This: 有了这个:

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

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

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