需要從SQL查詢中返回一個值,如表中記錄數。可以使用ExecuteScalar()方法,這個方法只返回一個值。如下邊控制台應用程序代碼所示:
using System.Data;
using System.Data.SqlClient;
namespace ExecuteScalar
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "select count(*) from customers";
//ExecuteScalar:執行只返回一個值的SQL命令。
object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers={0}",countResult);
Console.ReadLine();
thisConnection.Close();
}
}
}
結果為:
Count of Customers=91