计算行数(对于表)的错误 [英] Error on calculate counts of rows (for a table)
问题描述
你好
我写了一个网络服务。
$ c $ b在cs文件中我写了下面的线条。运行后,它返回1.
但是mytable中有很多行。
hello
i write a webservice.
in the cs file i write bellow lines. after run, it returns 1.
but there are many rows in mytable.
SqlConnection con = new SqlConnection("Data Source=mypc;Initial Catalog=myDB;User ID=admin;Password=admin123");
SqlCommand cmd;
SqlDataReader dr;
DatatableToJson dts = new DatatableToJson();
long id = 0;
string Table_Name = "";
[WebMethod]
public void OnlineUsers_Counts()
{
DataTable dt = new DataTable();
SqlCommand myCMD = new SqlCommand();
myCMD.CommandText = "select count(*) from OnlineUsers ";
con.Close();
con.Open();
myCMD.Connection = con;
dr = myCMD.ExecuteReader();
dt.Clear();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
Context.Response.Write(dt.Rows.Count.ToString());
}
谢谢
我是什么尝试过:
i无法解决问题。
help
thanks
What I have tried:
i couldn't do any things for solve the problems.
help
推荐答案
嗯。你得到1,不是吗?
那是因为
Um. You get 1, don't you?
That's because
SELECT COUNT(*) FROM MyTable
返回单行,其中包含一个字段,其中包含数字原始表中的行...
我使用ExecuteScalar返回单个值 - 行数 - 而不是ExecuteReader。
Returns a single row, with a single field in, which contains the number of rows in the original table...
I'd use ExecuteScalar which returns a single value - the number of rows - instead of ExecuteReader.
select count(*) from OnlineUsers
ExecuteReader()方法将以表格形式检索此数据。将有一行包含一个字段。
您可以做的是更改方法;使用 ExecuteScalar();
。所需的代码也会缩短几行。
The ExecuteReader() method is going to retrieve this data as a table. There will be one row with one field.
What you can do is to change the method; use ExecuteScalar();
. The needed code is a few lines shorter as well.
int RowCount = myCMD.ExecuteScalar();
Context.Response.Write(RowCount);
// dr = myCMD.ExecuteReader();
//
// dt.Clear();
// dt.Load(dr);
// if (dt.Rows.Count > 0)
// {
// Context.Response.Write(dt.Rows.Count.ToString());
// }
如果我可以添加到提供的解决方案,我强烈建议您执行以下操作:
(1)始终放置应用程序级别配置,例如y我们在web.config
文件中的连接字符串,这样您就不必在修改连接字符串时重新编译和重新部署代码。
(2)在 SqlConenction 和SqlCommand
href =https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement>使用块,因此对象在使用后将自动处理。这是一个简单的例子:
If I may add to the solution provided, I would strongly recommend you do the following:
(1) Always put app level configuration such as your connection string in yourweb.config
file so you won't have to recompile and redeploy your code when you modify your connection string.
(2) Wrap objects that eat resources such asSqlConenction
andSqlCommand
within a using block so objects will be automatically disposed after using them. Here's a quick example:
[WebMethod]
public void OnlineUsers_Counts()
{
int rowCount = 0;
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE")){
using(SqlCommand cmd = new SqlCommand("SELECT count(*) FROM OnlineUsers" , connection)){
cmd.CommandType = CommandType.Text;
rowCount = cmd.ExecuteScalar();
}
Context.Response.Write(rowCount);
}
这篇关于计算行数(对于表)的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!