C#中的ExecuteScalar方法用于執行查詢并返回結果集中的第一行的第一列的值。以下是ExecuteScalar方法的常見用法:
string queryString = "SELECT COUNT(*) FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
int count = (int)command.ExecuteScalar();
Console.WriteLine("Total number of customers: " + count);
}
string queryString = "SELECT FirstName FROM Customers WHERE LastName = @LastName";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@LastName", "Smith");
connection.Open();
string firstName = (string)command.ExecuteScalar();
Console.WriteLine("First name of the customer: " + firstName);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("GetTotalSales", connection);
command.CommandType = CommandType.StoredProcedure;
connection.Open();
decimal totalSales = (decimal)command.ExecuteScalar();
Console.WriteLine("Total sales: " + totalSales);
}
需要注意的是,在使用ExecuteScalar方法時,需要根據查詢返回的數據類型來進行強制類型轉換。在處理返回值之前,還應該進行必要的錯誤檢查和異常處理。