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

How to Get the Row Count from an SQL Query in C#?

DDD
Release: 2024-12-26 22:25:10
Original
411 people have browsed it

How to Get the Row Count from an SQL Query in C#?

Retrieving SQL Query Count inCSharp

To retrieve the count returned by an SQL query into an integer variable in C#, the most straightforward approach is to utilize SqlCommand.ExecuteScalar(). This method executes the provided SQL command and retrieves a single value from the first column and first row of the result set. For the given SQL query that counts rows in a table, the count can be captured into an int variable as follows:

using System.Data;
using System.Data.SqlClient;

// Create a connection string.
string connectionString = "your-connection-string";

// Create a connection object.
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Create a command object.
    using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection))
    {
        // Open the connection.
        connection.Open();

        // Execute the command.
        object scalarValue = cmd.ExecuteScalar();
        
        // Cast the scalar value to an integer.
        int count = (int)scalarValue;
    }

    Console.WriteLine($"Count: {count}");
}
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template