Csharp/C#教程:如何计算c#中sql表的行数?分享


如何计算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

上述就是C#学习教程:如何计算c#中sql表的行数?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1038836.html

(0)
上一篇 2022年1月26日
下一篇 2022年1月26日

精彩推荐