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

限于喜欢 提交于 2019-12-04 01:59:54

问题


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. While debugging I take the query and execute in MS ACCESS 2013, it gives me correct result. I am not getting what is the issue.


回答1:


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.

When running a query from within Access itself you need to use the asterisk as the wildcard character: 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%'.




回答2:


Try ExecuteScalar() method

Replace This:

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

With This:

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


来源:https://stackoverflow.com/questions/21016044/like-query-on-an-access-database-via-c-sharp-always-returns-count-of-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!