命令对象SqlCommand(二)执行命令,返回单个记录

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类型,如果把值赋给变量,注意数据类型转换.

posted on 2012-07-17 22:05  流星落  阅读(321)  评论(0编辑  收藏  举报

导航