1

I believe this is very simple, but I have spent a while Googling and looking at available API and I have not found a solution yet.

I simply need to get a data element (a double, in this case) from a known SQL table, when I know the Column and Row to get the data from, into my C# code. For simplicity, let's say my table has 3 columns: ProductID, Price, and Weight. I have access in my C# code to the ProductID, and I made a string which is the ProductID. Now I simply need to get that ProductIDs corresponding Price into a double in my C# code.

I am brand new to SQL, but I believe a pseudoquery would be something like:

SELECT Price FROM tablename WHERE ProductID=id

Not too worried about the query (but I would appreciate help with that as well). I just really need to know how to make a double in C# equal to that specific data element in the SQL table. It should be dead simple, but I am making it harder than it is. Here is some of the C# code so far:

SqlCommand sqlcommand = new SqlCommand("SELECT Price FROM tablename WHERE ProductID=id");
double ItemPrice = sqlcommand.GetData;
2
  • I don't see "GetData" as a method in the SqlCommand class. Commented Jul 15, 2013 at 17:01
  • Yea, I should have specified, that is kind of pseudocode. That's exactly the part that I don't know for sure what to use there. Commented Jul 15, 2013 at 17:05

1 Answer 1

2

What you want is ExexuteScalar on the command object.

For example:

var cmd = new SqlCommand(connection);
cmd.CommandText = "select price from products where id = 123";
var price = (double)cmd.ExecuteScalar();

MSDN Documentation here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

The word "scalar" comes from the mathematics world, and basically just means "a single quantified value".

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is exactly what I need. The dataset returned by the query should be only 1 item, so it would just pull that 1. Thanks.
Sure. ExecuteScalar technically returns the first column of the first row, regardless of the size of the returned data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.