MrM
MrM

Reputation: 21999

Read single value from query result

I am trying to return the result that I found in my query to the ASP.net table. How do I do that? I already have the query, I am just having trouble getting the count result back.

string configMan.ConnString["connect"].ToString();
iDB2Conn temp = new iDB2Conn
string query = "select Count(*) as total from test";
...

this is where I am having trouble.

Upvotes: 0

Views: 3208

Answers (3)

tghw
tghw

Reputation: 25313

This is where the SqlCommand object comes in handy.

int result = 0;
using(SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    SqlCommand sql = new SqlCommand("SELECT COUNT(*) FROM test", conn);
    result = (int)sql.ExecuteScalar();
}

Upvotes: 11

JD Conley
JD Conley

Reputation: 2936

Try using the ExecuteScalar method on your command. You should be able to use the generic one or cast the result to an int/long.

Upvotes: 0

Joe Doyle
Joe Doyle

Reputation: 6383

In ADO.Net, the simplest way is to use the ExecuteScalar() method on your command which returns a single result. You don't explicitly list what database or connection method you are using, but I would expect that most database access methods have something equivalent to ExecuteScalar().

Upvotes: 0

Related Questions