从c#运行查询时,发现MS Access数据库的行为非常奇怪。看来如果MS Access中的查询包含“like”语句,它将不会将其结果返回给Oledb。如果有人知道如何解决这个问题,我将非常感激。 c#代码:
DataTable GetAccessData(string FileName, string Password)
{
Query = "select * from [qry_1]";
DataTable DT = access2dt
(
FileName,Password,Query);
MessageBox.Show(Query);
if (DT == null || DT.Rows.Count <= 1) throw new Exception("Data not found");
else return DT;
}
public static DataTable access2dt(string filename, string password, string query)
{
string conString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Jet OLEDB:Database Password=" + password;
OleDbConnection mycon;
mycon = new OleDbConnection(conString);
if (mycon.State == ConnectionState.Closed)
{
mycon.Open();
}
try
{
OleDbCommand accessCommand = new OleDbCommand();
System.Data.DataTable dt = new System.Data.DataTable();
accessCommand = new OleDbCommand(query, mycon);
using (OleDbDataReader myReader = accessCommand.ExecuteReader())
{
DataTable myTable = new DataTable();
myTable.Load(myReader);
return myTable;
}
}
finally
{
mycon.Close();
}
}
MS Access数据库中保存的查询[qry_1]如下所示:
SELECT tbl_MAPPING_GICM_AoA.[Type of expense]
FROM tbl_USGAAP_ALL_TRANS, tbl_MAPPING_GICM_AoA
WHERE tbl_USGAAP_ALL_TRANS.[Account]=[tbl_MAPPING_GICM_AoA].[Natural Account]
AND tbl_USGAAP_ALL_TRANS.[Created By] NOT IN (SELECT [Created by / User ID] FROM tbl_GICM_AoA_EXCL_FACTOR1)
AND tbl_USGAAP_ALL_TRANS.[Je Source] NOT IN (SELECT [JE SOURCE] FROM tbl_GICM_AoA_EXCL_FACTOR2)
AND tbl_USGAAP_ALL_TRANS.[Je Category] NOT IN (SELECT [JE CATEGORY] FROM tbl_GICM_AoA_EXCL_FACTOR3)
AND (tbl_USGAAP_ALL_TRANS.[Account] LIKE '4*' OR tbl_USGAAP_ALL_TRANS.[Account] LIKE '5*' OR tbl_USGAAP_ALL_TRANS.[Account] LIKE '6*' )
因此,当我在Access中运行它时工作得很好,但是当我从c#调用此查询时,我得到“未找到数据”异常。如果我在查询中删除最后一个字符串(使用LIKE),一切都开始工作
答案 0 :(得分:6)
尝试替换通配符。 Access使用'*',但使用OLEDB,您需要使用'%'作为通配符。