数据库中的ExecuteScalar运用,常常与聚合函数一起使用,用于统计数据库中的某个字段的个数,最大值,最小值,平均值等。下面就是统计注册表中的用户个数
`using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExecuteScalar_test
{
class Program
{
static object o;
static void Main(string[] args)
{
string connStr = @”server=.;database=MyDB;uid=sa;pwd=123;integrated security=true”;
string sql = “select count(*) from Table_loginTest;”;
//string sql = string.Format(“insert into Table_loginTest(uid,pwd)values(‘{0}’,’{1}’)”, uid, pwd);
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
o = cmd.ExecuteScalar();
conn.Close();
Console.WriteLine(o);
}
}
Console.ReadLine();
}
}
}
`