I'd suggest that the best option here isn't actually a SqlDataAdapter
and DataSet
, but rather a SqlCommand
. Try this:
using(SqlConnection conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlCommand command = new SqlCommand("select total_amount from debit_account where account_no=12", conn)
{
var result = command.ExecuteScalar();
Console.WriteLine("The total_amount for the account is {0}", result);
}
}
The ExecuteScalar()
method on SqlCommand
returns the value in the first column of the first row that your query returns, which is ideal in this situation.
If you absolutely have to use a dataset then you'd want to do the following:
using(SqlConnection conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true"))
{
conn.Open()
using (SqlDataAdapter adapter = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn)
{
var ds = new DataSet();
adapter.Fill(ds);
Console.WriteLine("The total_amount for the account is {0}", ds.Tables[0].Rows[0][0]); // Get the value from the first column of the first row of the first table
}
}
Note: I've wrapped both examples in the C# using
statement, this ensures that all your database resources are cleaned up so you don't have any problems with with leaking unmanaged resources. It's not particularly difficult or complicated so is well worth doing