Reputation: 1357
I am trying to return INTEGER
value from Oracle Database using C# but it is giving me following Exception
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Additional information: Specified cast is not valid.
Can anyone help me to resolve this?
Here is my code:
OleDbConnection con = new OleDbConnection(
"Provider=MSDAORA;Data Source=xe;User ID=hr; password=123");
con.Open();
String cmd1 =
@"select retail_price,purchase_price from
productdetails where item_name='" + textBox1.Text + "'";
OleDbCommand a1 = new OleDbCommand(cmd1, con);
OleDbDataReader myReader = a1.ExecuteReader();
if (myReader.Read())
{
int m = myReader.GetInt32(0);
MessageBox.Show("" +m);
}
Upvotes: 2
Views: 1413
Reputation: 186668
First of all, according to the query
select retail_price,
purchase_price
from productdetails
where item_name = :item_name
the actual type of retail_price
as well as purchase_price
can be some floating point value type (double
or decimal
; say, 8.95$ == 8.95
):
decimal retail_price = Convert.ToDecimal(myReader[0]);
decimal purchase_price = Convert.ToDecimal(myReader[1]);
If you insist on integers, round them up (8.95$ == 8.95 -> 9
); assuming prices are non-negative:
int retail_price = (int) (Convert.ToDouble(myReader[0]) + 0.5);
int purchase_price = (int) (Convert.ToDouble(myReader[1]) + 0.5);
Upvotes: 2
Reputation: 10680
Happening for a couple of reasons.
First, your price fields are likely to be decimal. Next, you probably need to be more explicit when accessing fields on your reader.
Try:-
int purchasePriceint = Convert.ToInt32(myReader["purchase_price"]);
int retailPriceint = Convert.ToInt32(myReader["retail_price"]);
Upvotes: 1