Search code examples
c#winformsms-accessoledb

How to retrieve data from more then two table of MS Access database using c#


I want to retrieve data from MS Access database from 3 tables connected with each other.
I wrote this code in business layer

public List<ProductOrderModel> Show()
{
         OleDbConnection cn;
         try
         {
             ProductOrderModel dtoobj = new ProductOrderModel();
             DataLayer dalobj = new DataLayer();
             OleDbCommand cmdshow = new OleDbCommand();

             cmdshow.CommandText = "select [CustomerVT].[Customer_Name],[OrderVT].[Order_Date],[ProductVT].[Price],[ProductVT].[Item_Name],[OrderVT].[Quantity],[OrderVT].[Order_ID] from  [OrderVT] inner join [CustomerVT] on [OrderVT].[Customer_ID]=[CustomerVT].[Customer_ID] inner join [ProductVT] on [OrderVT].[Product_ID]=[ProductVT].[Product_ID] ";

              List<ProductOrderModel> Ldemo = new List<ProductOrderModel>();

             return dalobj.executereader(Ldemo, cmdshow, "BillingData");
   }
   catch (Exception ex2)
   {
       throw new DataException("error....." + ex2.Message);
   }
}

and code for ExecuteReader() is..

public List<ProductOrderModel> executereader(List<ProductOrderModel> Ldemo, OleDbCommand cmdshow, string tablename)
{
        OleDbConnection cn;

        try
        {
            cn = this.getconnection();

            cmdshow.Connection = cn;
            cn.Open();

            OleDbDataReader rd = cmdshow.ExecuteReader();

            while (rd.Read())
            {
                ProductOrderModel dtoobj1 = new ProductOrderModel();

                dtoobj1.InvoiceNo = Convert.ToInt32(rd["Order_ID"].ToString());
                dtoobj1.CustomerName = rd["Customer_Name"].ToString();

                dtoobj1.ItemName = rd["Item_Name"].ToString();
                dtoobj1.Quantity = Convert.ToInt32(rd["Quantity"].ToString());
                dtoobj1.Price = Convert.ToInt32(rd["Price"].ToString());
                dtoobj1.OrderDate = Convert.ToDateTime(rd["Order_Date"].ToString());
                Ldemo.Add(dtoobj1);
            }

            cn.Close();
            return Ldemo;
        }
        catch (Exception ex2)
        {
            throw new DataException("error....." + ex2.Message);
        }
}

but it shows error

Syntax error (missing operator) in query expression '[OrderVT].[Customer_ID]=[CustomerVT].[Customer_ID] inner join [ProductVT] on [OrderVT].[Product_ID]=[ProductVT].[Product_ID]'

please help. thanks in advance.


Solution

  • use parentheses like below

    select [CustomerVT].[Customer_Name],[OrderVT].[Order_Date],[ProductVT].[Price],[ProductVT].[Item_Name],[OrderVT].[Quantity],[OrderVT].[Order_ID] 
    from  ([OrderVT] 
    inner join [CustomerVT] on [OrderVT].[Customer_ID]=[CustomerVT].[Customer_ID])
    inner join [ProductVT] on [OrderVT].[Product_ID]=[ProductVT].[Product_ID]