How to count the number of rows from sql table in C #?

How to count the number of rows from sql table in C #? I need to extract some data from my database ...

+7
source share
5 answers

You can try the following:

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

C # code would be something like this: -

 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; } 
+28
source

First you need to connect to the database from C #. Then you need to pass the request below as commandText.

Select count(*) from TableName

Use ExecuteScalar / ExecuteReader to get a refundable invoice.

+4
source

You like this?

 SELECT COUNT(*) FROM yourTable WHERE .... 
+3
source

You can make a global function that you can use all the time as

  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; } } 
+1
source

It works for me

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

For more information, refer to: https://docs.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN

0
source

Source: https://habr.com/ru/post/958692/


All Articles