Reputation: 31
I use SQL Server to build my database and SqlDataReader to read data from it.
command.Connection = cn;
command.CommandText = "SELECT * FROM test";
SqlDataReader rd = command.ExecuteReader();
while(rd.Read())
{
double d = (double) rd.GetValue(0);
}
The column (0) I am trying to get value from is a 'float' type and has value '3.5' . As mapping data type from this MSDN link, the type of the object returned by rd.GetValue(0) must be 'double'. But the code above returns to variable 'd' value '0.0'. I tried this line:
double d = Convert.ToDouble(rd.GetValue(0));
But it still returns '0.0' to variable 'd'.
I tried searching on Google and StackOverflow but there is no result.
What am I missing? Help me!
Upvotes: 1
Views: 1846
Reputation: 31
Oh I have found the answer. Nothing wrong with the code I wrote. The problem is that I place the breakpoint on the 'double d = (double) rd.GetValue(0)' line. That is, 'd' value is not assigned yet so that on the debug screen it returns '0.0'. Sorry for this mistake and thank you all Stack-Over-flowers for spending your time helping me!!!!
Upvotes: 1
Reputation:
you can try it;
double d = (double) rd.GetValue(0);
to
double d = 0;
double.TryParse(rd["ColumnName"].ToString().Replace('.',','),out d);
OR:
double d = double.Parse(rd["ColumnName"].ToString(), CultureInfo.InvariantCulture);
Upvotes: 2
Reputation: 3591
This here works fine for me, im getting 3,5 in my list
List<double> columnData = new List<double>();
using (SqlConnection connection = new SqlConnection("Server=EGC25199;Initial Catalog=LegOgSpass;Integrated Security=SSPI;Application Name=SQLNCLI11.1"))
{
connection.Open();
string query = "SELECT * FROM [dbo].[floattable]";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetDouble(0));
}
}
}
}
Upvotes: 1
Reputation: 14389
As it is now, your code iterates over all the records (if there are many) an takes the last entry, which since you have no order by
clause, may differ in every query execution. If indeed you want to only take 1 value, use ExecuteScalar
together with an order by
clause:
command.Connection = cn;
command.CommandText = "SELECT TOP 1 * FROM test order by myfield desc"; //or asc
double result = (double)command.ExecuteScalar();
Otherwise have all the result saved in a list:
...
List<double> result = new List<doulbe>();
while(rd.Read())
{
result.Add(double.Parse(rd[0].ToString());
}
Finally, if you need only the 1st field, for performance reasons, is far better not to use * but explicit set the field you want:
"SELECT TOP 1 myfield FROM test order by myfield desc"; //or asc
Upvotes: 2