2017년 2월 13일 월요일

[C#/닷넷/xamarin/WPF교육/C#네트워크교육학원추천_탑크리에듀][ExecuteScalar를 이용하여 테이블 행의 개수를 가져오는 예제]

[ExecuteScalar를 이용하여 테이블 행의 개수를 가져오는 예제]

테이블 행의 개수를 알아 내는 것으로 DataReader의 경우와 비슷하나 실행 메소드를 다른 것을 사용한다. (DataReader의 경우 ExecuteReader) 

임의의 데이터에 대해 어떤 조작을 해야 한다면 DataSet에 데이터를 채울 것이므로 따라서 DataTable.Rows.Count를 이용하여 행들의 개수를 얻으면 되지만 테이블이 매우 큰 경우에 그 개수를 알기 위해 DataSet에 데이터를 찿우고 DataTable.Rows.Count 를 실행하기에는 오버헤드가 있다. 

이 경우 ExecuteScalar()를 통해 select count(*) 질의를 수행 하는 것이 훨씬 효율적 입니다.

[예제] Oracle scott 계정의 EMP 테이블 레코드 건수 리턴 …

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbConnection Cn = null;
            try
            {
                string conStr = "Provider=MSDAORA;data source=onj;User ID=scott;Password=tiger";
                Cn = new OleDbConnection(conStr);
                OleDbCommand cmdSelect = new OleDbCommand("select count(*) from emp", Cn);
                Cn.Open(); object count = cmdSelect.ExecuteScalar();
                Console.WriteLine("Count of Emp = {0}", count);
                Cn.Close();
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            finally
            {
                if (Cn.State == ConnectionState.Open)

                { Cn.Close(); }
            }
        }
    }
}

[결과]
Count of Emp = 22

댓글 없음:

댓글 쓰기