LIKE query on an Access database via C# always ret

2019-02-19 13:38发布

问题:

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