Related knowledge:
- Some SQL operations, such as SUM, return only one data value from the database, not multiple rows of data
- Although you can also use ExecuteReader () to return a DataReader object that represents that data value, it is more convenient to use the ExecuteScalar method of the Command object
- ExecuteScalar () Method: The method can only execute SELECT statements and is typically used for statistics, such as returning the number of records that match a condition
code example:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSystem.Data;7 usingSystem.Data.SqlClient;8 9 namespaceConsoleApplication3Ten { One class Program A { - Static voidMain (string[] args) - { the stringstrconn =@"Server=joe-pc;database=adventureworks_wroxssrs2012;uid=sa;pwd=root"; -SqlConnection conn =NewSqlConnection (strconn); - - stringStrcmd ="SELECT COUNT (*) from Production.productcategory"; +SqlCommand cmd =NewSqlCommand (STRCMD, conn); - + Conn. Open (); A at intCount = Convert.ToInt32 (cmd. ExecuteScalar ());//ExecuteScalar Returns an object type - -Console.WriteLine ("there are {0} rows of data. ", count); - - Conn. Close (); - } in } -}
Ado. NET QuickStart-Returns a data value using the ExecuteScalar () method of the Command object