Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading int values from SqlDataReader

Tags:

c#

ado.net

hi can anyone please help me with this fetching from database of int values im having difficulty in fetching int values , it works for varchar but not int can someone help me out please

if (int.TryParse(TxtFarmerCode.Text, out intValue)) {    using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True")) //here goes connStrng or the variable of it    {       sqlConn.Open();       string sqlQuery = @"SELECT farmername,villagename,gender,farmsize FROM cottonpurchase WHERE farmercode = @code";        using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))       {          cmd.Parameters.Add("@code", SqlDbType.Int).Value = intValue;          using (SqlDataReader reader = cmd.ExecuteReader())          {;             if (reader.Read())             {                TxtFarmerName.Text = (string)reader[0];                TxtVillageName.Text = (string)reader[1];                TxtGender.Text = (string)reader[2];             }             else                MessageBox.Show("For Farmer Code " + intValue.ToString() + " there is no farmer in the database.");          }       }    } } 

i want to fetch txtfarmersize which is int but dont know how to do it please help me?

like image 249
tanya Avatar asked Sep 12 '11 13:09

tanya


People also ask

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

What does SqlDataReader read do?

The SqlDataReader is used to read a row of record at a time which is got using SqlCommand. It is read only, which means we can only read the record; it can not be edited. And also it is forward only, which means you can not go back to a previous row (record).

Does SqlDataReader need to be disposed?

You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.

How does SqlDataReader work in C#?

SqlDataReader objects allow you to read data in a fast forward-only manner. You obtain data by reading each row from the data stream. Call the Close method of the SqlDataReader to ensure there are not any resource leaks.


1 Answers

you can use

reader.GetInt32(3); 

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName))  

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

like image 96
Sam Holder Avatar answered Sep 24 '22 20:09

Sam Holder