如何计算c#中sql表的行数?

时间:2013-11-23 09:57:36

标签: c# asp.net sql database

如何计算c#中sql表的行数? 我需要从我的数据库中提取一些数据......

6 个答案:

答案 0 :(得分:28)

您可以尝试这样:

select count(*) from tablename where columname = 'values'

C#代码将是这样的: -

public int A()
{
   string stmt = "SELECT COUNT(*) FROM dbo.tablename";
   int count = 0;

   using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
   {
       using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
       {
           thisConnection.Open();
           count = (int)cmdCount.ExecuteScalar();
       }
   }
   return count;
}

答案 1 :(得分:4)

您需要先从c#建立数据库连接。然后,您需要将以下查询作为commandText传递。

Select count(*) from TableName

使用ExecuteScalar / ExecuteReader获取返回的计数。

答案 2 :(得分:3)

你的意思是喜欢这个吗?

SELECT COUNT(*) 
FROM yourTable 
WHERE ....

答案 3 :(得分:1)

您可以创建一直可以使用的全局功能

    public static int GetTableCount(string tablename, string connStr = null)
    {
        string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
        if (String.IsNullOrEmpty(connStr))
            connStr = ConnectionString;
        int count = 0;
        try
        {

            using (SqlConnection thisConnection = new SqlConnection(connStr))
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
                {
                    thisConnection.Open();
                    count = (int)cmdCount.ExecuteScalar();
                }
            }
            return count;
        }
        catch (Exception ex)
        {
            VDBLogger.LogError(ex);
            return 0;
        }
    }

答案 4 :(得分:0)

这对我有用

using (var context = new BloggingContext())
{
   var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}

有关更多信息,请参见:https://docs.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN

答案 5 :(得分:0)

使用它的工作

        string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";

        connect.Open();

        SqlCommand cmd = new SqlCommand(strQuery, connect);
        SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
        DataSet dsData = new DataSet();
        OleDbDa.Fill(dsData);

        connect.Close();
        
        std.Text = dsData.Tables[0].Rows.Count.ToString();