Home >Database >Mysql Tutorial >How to Retrieve SQL Count Values as Integers in C#?
Capturing Results from an SQL Query: Retrieving Count Values
To effortlessly retrieve the count value from an SQL query into an integer variable in C#, utilize the SqlCommand.ExecuteScalar() method. This method executes the specified query and returns the first column's first row value.
Implementation:
To employ this technique, follow these steps:
Example Code:
using System; using System.Data; using System.Data.SqlClient; class Program { static void Main() { string connectionString = @"Data Source=(local);Initial Catalog=myDatabase;Integrated Security=SSPI;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection); Int32 count = (Int32)cmd.ExecuteScalar(); Console.WriteLine($"The count of records in table_name is {count}"); } } }
By leveraging this technique, you can conveniently capture and store count values from SQL queries in your C# code.
The above is the detailed content of How to Retrieve SQL Count Values as Integers in C#?. For more information, please follow other related articles on the PHP Chinese website!