我正在尝试使用标签从网格视图显示行数。我使用了SQL Count语句,但是它不起作用。问题是我只得到标签中显示的数字1,该数字与我表中的行数不匹配!我已经发布了类似的问题,但不幸的是没有人给出明确的答案!
我的代码为:
购物篮
public int td()
{
int customers;
//I tried this select query but still gets number 1
//String sql = String.Format("SELECT COUNT(*) FROM dbo.Baskets");
string sql = string.Format("SELECT COUNT(*) FROM Baskets");
customers = Db.RunQuery(sql).Rows.Count;
//customers = Convert.ToInt32(Db.RunQuery(sql).Rows.Count);
return customers;
}
数据库连接
public class DataBaseConn
{
SqlConnection conn;
SqlCommand cmd;
DataTable tbl;
private void Intialise(CommandType commandtype, string DataBase)
{
conn = new SqlConnection();
cmd = new SqlCommand();
//Requirements
conn.ConnectionString = ConfigurationManager.ConnectionStrings[1].ToString();
cmd.Connection = conn;
cmd.CommandType = commandtype;
cmd.CommandText = DataBase;
conn.Open();
}
public int RunProcedure(string Procedure, SortedList ParameterV)
{
Intialise(CommandType.StoredProcedure, Procedure);
for (int i = 0; i < ParameterV.Count; i++)
try
{
if (ParameterV.GetByIndex(i) != null)
cmd.Parameters.AddWithValue(ParameterV.GetKey(i).ToString(),
PrameterV.GetByIndex(i).ToString());
}
catch { ;}
return RunUpdate();
}
public int RunUpdate(string InsDelUpd)
{
Intialise(CommandType.Text, InsDelUpd);
return RunUpdate();
}
private int RunUpdate()
{
try
{
int x = cmd.ExecuteNonQuery();
conn.Close();
return x;
}
catch (SqlException ex)
{
conn.Close();
return ex.Number;
}
}
public DataTable RunQuery(string Select)
{
Intialise(CommandType.Text, Select);
tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
conn.Close();
return tbl;
}
public bool EData(string selection)
{
if (RunQuery(selection).Rows.Count > 0)
return true;
else
return false;
}
}
Basket.aspx
lblQueue.Text = _b.td().ToString();
您不想返回数据表的.Rows.Count
-1 row(s) affected
对于您的count(*)
查询,该值始终为1(如所示)。
您应该改用ExecuteScalar
查询从查询中返回第一行的第一列
我不确定如何将其构建到DataBaseConn
数据助手类中,但是要点是您需要按以下顺序进行:
using (var conn = new SqlConnection(connectionStringHere))
using (var cmd = new SqlCommand(conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT COUNT(*) FROM Baskets";
return (int)cmd.ExecuteScalar();
}
编辑
如果您无法使用扩展您的DataBaseConn
帮助器ExecuteScalar
,那么我想您将可以使用RunQuery
返回DataTable的现有方法。只需刮擦第一行的第一列,如下所示:
return Db.RunQuery(sql).Rows[0].Field<int>(0);
附带说明一下,您可能会考虑将其DataHelper
完全替换为Microsoft模式和实践数据应用程序访问块(DAAB),或者,如果愿意,可以考虑使用诸如Entity Framework之类的ORM 。通过升级到主流的数据访问封装,您将不需要花费很多时间来调试像这样的数据访问问题:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句