开发者

how to print single value of data set

conn = new SqlConnection(@"Data Source=ASHISH-PC\SQLEXPRESS; initial catalog=bank; integrated security=true");
ada = new SqlDataAdapter("select total_amount from debit_account where account_no=12", conn);
ds = new DataSet();

ada.Fill(ds开发者_JAVA技巧);

Now, I want to print value of the dataset... how? Please help me.


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


I think, in this case, you'd be better off (performance-wise) to use a SqlCommand instead of the adapter and dataset, and invoke the ExecuteScalar method.

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

If you must use the data set, however, ds.Tables[0].Rows[0]["total_amount"] should retrieve your value. You will probably need to type cast the value, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜