Search code examples
c#.netoracleoraclecommand

Specified cast is not valid. Is it because I am attempting to cast an object?


I have the following C# code that I am using to attempt to query an oracle database. I am simply trying to get the numeric result so that I can output it to the console and eventually hold it in a variable.

I keep getting the following error though:

System.InvalidCastException: Specified cast is not valid at Oracle.DataAccess.Client.OracleDataReader.GetInt32(Int32 i)

I am using VS 2012 on a windows professional machine. Please let me know if I need to add additional info. Any help greatly appreciated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System.Configuration;
using System.Data.SqlClient;

namespace OB_837_File_Reconciliation_Rpt_Automation
{
  class Program
  {
    static void Main(string[] args)
   {
      OracleConnection dbConnection;
      string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=             (PROTOCOL=TCP)(HOST=*******)(PORT=******))(CONNECT_DATA=(SERVICE_NAME=******)));User ID=*****;Password=*********";
        try
        {
            dbConnection = new OracleConnection(connectionString);                
            string query = "select count (*) AS AMG_Prof from wellmed_owner.claim c inner join WELLMED_OWNER.payment_detail pd on c.claim_id = pd.claim_id where c.claim_status in ('6','8','C') and c.insured_group_id in ('ASA','AEP') and c.form_type = '1' and trunc(pd.paid_date) = trunc(sysdate -4)";
            dbConnection.Open();
            OracleCommand comm = new OracleCommand(query, dbConnection);               
            OracleDataReader rdr = comm.ExecuteReader();
            rdr.Read();                
            int count = (int)comm.ExecuteScalar();
            Console.WriteLine(count);
            //int num = rdr.GetInt32(0);
            //Console.WriteLine(count);              
            Console.WriteLine("Connecting Okay");

       }
     catch (Exception e)
     {
       Console.WriteLine(e);
     }

        }
    }
}

Solution

  • use ExecuteScalar

    dbConnection.Open();
    OracleCommand comm = new OracleCommand(query, dbConnection);               
    decimal count = (decimal)comm.ExecuteScalar();
    Console.WriteLine(count);              
    Console.WriteLine("Connecting Okay");