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方法时,需要根据查询返回的数据类型来进行强制类型转换。在处理返回值之前,还应该进行必要的错误检查和异常处理。