ExecuteScalar: 执行查询,并返回查询结果集中第一行的第一列(object类型)。
返回一个System.Object类型的数据,因此我们在获取数据时需要进行强制类型转换。
如果找不到结果集中第一行的第一列,,ExcuteScalar方法返回System.DBNull,即返回 null 引用。
案例代码:取tb_user中的行数(超出百万行)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ExcuteScalar
{
class Program
{
static void Main(string[] args)
{
//1.构造连接字符串的方法
SqlConnectionStringBuilder connStr = new SqlConnectionStringBuilder();
connStr.DataSource = "192.168.1.20";
connStr.InitialCatalog = "mshDB_Debug";
connStr.UserID = "developer";
connStr.Password = "developer";
connStr.Pooling = true;
connStr.MaxPoolSize = 1000;
connStr.MinPoolSize = 1;
//2.创建Connection对象
SqlConnection conn = new SqlConnection(connStr.ToString());
//3.拼接SQL语句
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from tb_user");
//4.创建Command对象
SqlCommand cmd = new SqlCommand(strSql.ToString(), conn);
cmd.CommandType = CommandType.Text;
//5.执行SQL语句
try
{
conn.Open();
int rows = (int)cmd.ExecuteScalar(); //执行命令
Console.WriteLine("执行ExcuteScalar方法:共{0}行记录", rows);
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
}
运行如下: