C# 如何打印数据集的单个值
现在,我想打印数据集的值。。。怎样?请帮帮我。我认为,在这种情况下,最好使用C# 如何打印数据集的单个值,c#,ado.net,C#,Ado.net,现在,我想打印数据集的值。。。怎样?请帮帮我。我认为,在这种情况下,最好使用SqlCommand而不是适配器和数据集,并调用ExecuteScalar方法 看 但是,如果必须使用数据集,ds.Tables[0]。行[0][“总计金额”]应检索您的值。不过,您可能需要键入cast值。我建议这里的最佳选项实际上不是SqlDataAdapter和DataSet,而是SqlCommand。试试这个: conn = new SqlConnection(@"Data Source=ASHISH-PC\SQL
SqlCommand
而不是适配器和数据集,并调用ExecuteScalar
方法
看
但是,如果必须使用数据集,
ds.Tables[0]。行[0][“总计金额”]
应检索您的值。不过,您可能需要键入cast值。我建议这里的最佳选项实际上不是SqlDataAdapter
和DataSet
,而是SqlCommand
。试试这个:
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);
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);
}
}
注意:我已将这两个示例包装在C#中,这可确保清理所有数据库资源,因此不会出现泄漏非托管资源的问题。这并不特别困难或复杂,因此非常值得做设置一些控件的数据源,如datagrid/repeater等,具体取决于您希望显示结果的方式,然后执行dataBind,例如datagrid display=new datagrid();display.DataSource=ds;display.DataBind()+1.此示例已完成并正确处理了
IDisposable
类。@ashish,如果它回答了您的问题,请单击此答案左侧的空心勾号,将其标记为您的“已接受答案”=)
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
}
}