SQL代码返回单个值,应该使用SqlCommand对象的ExceuteScalar方法
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.SqlClient;namespace CommandScalar{ class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection(@"Data Source=PC2012032219VBB;Initial Catalog=Northwind;Integrated Security=True"); //create command(with both text and connection) string sql = @"select count(*) from employees"; SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); Console.WriteLine("Number of Employees is {0}", cmd.ExecuteScalar()); } catch (SqlException ex) { Console.WriteLine(ex.ToString()); } finally { conn.Close(); Console.WriteLine("Connection Closed."); } Console.ReadKey(); } }}
cmd.ExecuteScalar()返回的是object类型,如果把值赋给变量,注意数据类型转换.