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

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

你可以尝试这样:

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; } 

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

Select count(*) from TableName

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

你的意思是喜欢这个吗?

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

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

  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; } }