Home >Database >Mysql Tutorial >How to Get the Record Count from a SQL Query in C#?

How to Get the Record Count from a SQL Query in C#?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 05:59:09441browse

How to Get the Record Count from a SQL Query in C#?

Capturing Record Count from a SQL Query in C

Retrieving the number of records returned by a SQL query into an integer variable in C# can be achieved with ease.

Solution:

The most straightforward approach involves utilizing the SqlCommand.ExecuteScalar() method. This method executes the SQL command and returns a single value as the output. To capture the count returned by the COUNT(*) expression, simply cast the result to an integer:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
int count = (Int32)cmd.ExecuteScalar();

This code snippet assigns the integer representing the record count to the count variable, providing developers with a convenient way to work with the result of the SQL query.

The above is the detailed content of How to Get the Record Count from a SQL Query in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn