SQL 查询未返回正确的计数
我正在尝试计算行数并传递该计数值来执行一些逻辑。下面是代码:
static public int GetNoImagesofMakeID(int makeID)
{
string sql = "Select COUNT(*) from makeImages";
SqlDataAdapter da = new SqlDataAdapter(sql, ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
return Convert.ToInt32(dt.Rows.Count);
}
protected void hideUnhideFileUpload(int makeID)
{
int count = caravans.GetNoImagesofMakeID(makeID);
if (count >= 10)
{
FileUpload2.Enabled = false;
}
else
{
FileUpload2.Enabled = true;
}
}
我不知道为什么计数总是 1。我在 SQL Server 上检查了相同的查询,它工作正常。但是,这里 dt.rows.count 总是返回 1。
任何帮助将不胜感激。谢谢。
I am trying to count the number of rows and pass that count value to do some logic. Below is the code:
static public int GetNoImagesofMakeID(int makeID)
{
string sql = "Select COUNT(*) from makeImages";
SqlDataAdapter da = new SqlDataAdapter(sql, ConnectionString);
DataTable dt = new DataTable();
da.Fill(dt);
return Convert.ToInt32(dt.Rows.Count);
}
protected void hideUnhideFileUpload(int makeID)
{
int count = caravans.GetNoImagesofMakeID(makeID);
if (count >= 10)
{
FileUpload2.Enabled = false;
}
else
{
FileUpload2.Enabled = true;
}
}
I don't know for what reason the count is always 1. I checked the same query on SQL Server and it's working fine. But, here dt.rows.count always return 1.
Any help will be highly appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该代码返回行数而不是 COUNT(*) 的结果。该 SQL 语句将始终只返回一行。您无需填充数据适配器,只需运行以下命令即可:
The code is returning the number of rows rather than the result of the COUNT(*). That SQL statement will always just return a single row. Rather than filling a data adapter, you can just run the command:
您的查询返回具有一个值(行数)的一行,因此 dt.Rows.Count 正确返回 1(意味着您的查询返回 1 行)。
使用数据表,您可以在
dt.Rows[0][0]
(数据表的第 0 行第 0 列)处找到查询返回的计数Your query is returning one row with one value (the count of rows), so
dt.Rows.Count
is correctly returning 1 (meaning 1 row returned by your query).Using a datatable, you would find the count returned by your query at
dt.Rows[0][0]
(row 0 column 0 of your datatable)count() 始终返回一行,无论其计数有多少行。 count() 是一个标量值。您需要做的是读取记录集中返回的值。
有关此问题中计数的更多信息: SQL Return code from Select count(* )
A count() always returns a row, regardless of how many rows it is counting. a count() is a scalar value. What you need to do is read the value returned in the recordset.
More information about counts in this question: SQL Return code from Select count(*)
为什么您要获取表行数,而不是计数查询的返回值,因为这只会返回单行?
Why are you getting the table row count, instead of the returned value from your count query, as this will return only single row?