4
從c#運行查詢時發現MS Access數據庫非常奇怪的行爲。看來如果MS Access中的查詢包含「like」語句,它將不會將其結果返回給Oledb。如果有人知道如何解決這個問題,我將非常感激。 C#代碼:從c#運行MS Access保存的查詢#
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();
}
}
和查詢[qry_1]保存在MS Access數據庫看起來是這樣的:
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),則所有事情都開始工作
它的工作!現在查詢在Access中不起作用,但我不關心那麼多。謝謝! – Vadim 2012-03-29 11:51:16
@Vadim不客氣。 – 2012-03-29 13:02:00