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}"); }
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!