简体   繁体   English

如何使用SqlDataReader获取Sum结果

[英]How to get the Sum result with an SqlDataReader

I do a Sum() on my query but when I want to use a dataReader it is not working 我对查询执行Sum(),但是当我想使用dataReader时不起作用

I've tried this 我已经试过了

string request = "SELECT sum(price_product) as price FROM product";
SqlCommand command = new SqlCommand(request, loaddatabaseconnexion.connexion_BDD());
SqlDataReader dataReader = command.ExecuteReader();
cout_total_stock.Text = dataReader["price"].ToString();

There is no need for a SqlDataReader, you can just call ExecuteScalar from the SqlCommand when your query returns a single value (Sum,Max,Min, etc) 不需要SqlDataReader,当查询返回单个值(Sum,Max,Min等)时,只需从SqlCommand调用ExecuteScalar

decimal value = Convert.ToDecimal(command.ExecuteScalar());

However, if you really want to use an SqlDataReader then you should always call the Read method to 'move' the SqlDataReader internal position to the first record returned by your query 但是,如果您确实要使用SqlDataReader,则应始终调用Read方法将SqlDataReader内部位置“移动”到查询返回的第一条记录中。

SqlDataReader dataReader = command.ExecuteReader();

// Always check if Read returns false. 
// If false there is no record to Read.
if(dataReader.Read())
   cout_total_stock.Text = dataReader["price"].ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM