执行查询,并返回查询所返回的结果集中第一行的第一列,忽略其他行列。一般用来简单的获得只有一行一列的查询结果的值。
案例1:
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ADO.Net { class Program { static void Main(string[] args) { using (MySqlConnection conn = new MySqlConnection("server=127.0.0.1;uid=xiaoping;pwd=825991;database=test;Charset=utf8")) using (MySqlCommand cmd = conn.CreateCommand()) { conn.Open();//打开连接 cmd.CommandText = "select Count(*) from T_Users;"; int i = Convert.ToInt32(cmd.ExecuteScalar()); Console.WriteLine(i); } Console.ReadKey(); } } }
案例2:
cmd.CommandText = "Select Password from T_Users where UserName='admin'"; string pwd = (string)cmd.ExecuteScalar(); if (string.IsNullOrEmpty(pwd)) { Console.WriteLine("找不到admin"); } else { Console.WriteLine("admin的密码:" + pwd); }