如何打印数据集的单个值

ash*_*ish 2 c# ado.net

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);
Run Code Online (Sandbox Code Playgroud)

现在,我想打印数据集的值......怎么样?请帮我.

Rob*_*Rob 6

我建议在这里最好的选择实际上不是SqlDataAdapterDataSet,而是一个SqlCommand.试试这个:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

ExecuteScalar()对方法SqlCommand返回的第一行,你的查询返回,这是在这种情况下,理想的第一列的值.

如果您绝对必须使用数据集,那么您需要执行以下操作:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

注意: 我已经在C#using语句中包含了这两个示例,这可以确保清理所有数据库资源,这样您就可以避免泄漏非托管资源.这不是特别困难或复杂,所以值得做