如何打印数据集的单个值
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);
现在,我想打印数据集的值......如何?请帮我。
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);
Now, I want to print value of the dataset... how? Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议这里最好的选择实际上不是
SqlDataAdapter
和DataSet
,而是SqlCommand
。试试这个:ExecuteScalar()
方法返回查询返回的第一行第一列中的值,这在这种情况下是理想的。SqlCommand
上的如果您绝对必须使用数据集,那么您需要执行以下操作:
注意: 我已将这两个示例包装在 C#
using
语句,这确保您的所有数据库资源都已清理,因此您不会遇到任何泄漏非托管资源的问题。这并不是特别困难或复杂,所以非常值得做I'd suggest that the best option here isn't actually a
SqlDataAdapter
andDataSet
, but rather aSqlCommand
. Try this:The
ExecuteScalar()
method onSqlCommand
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:
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我认为,在这种情况下,您最好(从性能角度)使用
SqlCommand
而不是适配器和数据集,并调用ExecuteScalar
方法。请参阅 http://msdn.microsoft.com /en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
但是,如果您必须使用数据集,
ds.Tables[0].Rows[0]["total_amount" ]
应该检索您的值。不过,您可能需要对值进行类型转换。I think, in this case, you'd be better off (performance-wise) to use a
SqlCommand
instead of the adapter and dataset, and invoke theExecuteScalar
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.