首页 > 开发 > 综合 > 正文

counting Records in an SQL Table by G.F. Weis Gfw

2024-07-21 02:23:47
字体:
来源:转载
供稿:网友
counting records in an  sql table by g.f. weis gfw


--------------------------------------------------------------------------------

i was working on a project using my c# class generator  and realized that i had no way to get a count of the number of records in the table. in the past i have used the dataadapter class - easy, but not very efficient.

i ran accross a post on one of the discussion forums and decided to build a new function in my class generator appropriately named recordcount. the function returns an 'int' with the number of records in the table.

m_dbconnection is the connection string to your database
arepresentative is the name of our table
id is unique column used in our table
using the c# class generator, the generated code is as follows:


public int recordcount() // get count of records
{
    int reccount=0;
    string countcmd = "select count(id) as total from arepresentative ";
    sqlconnection m_sqlconnection = new sqlconnection(m_dbconnection);
    sqlcommand    m_sqlcommand    = new sqlcommand(countcmd, m_sqlconnection);
    try
    {
        // open the connection ----------------------------
        m_sqlcommand.connection.open();
        reccount = (int)m_sqlcommand.executescalar();
    } // end try
    catch (exception e)
    {
        throw new exception("error in recordcount() -> " + e.tostring());
    }
    finally
    {
        m_sqlconnection.close();
        m_sqlcommand.dispose();
    }
    return reccount;
} // end select
上一篇:DataSet的几个基本操作

下一篇:聚合函数

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表