프로그래밍 기술/SQL과 ADO.NET

[ADO.NET] SqlCommand 클래스 개요

언제나휴일 2016. 4. 22. 12:21
반응형

 

 SqlConnection 개체로 데이터 소스에 연결한 후에 필요한 구체적인 작업을 할 때 SqlCommand 개체를 사용합니다.

 

 SqlCommand 개체로 수행할 수 있는 작업은 쿼리문이나 저장 프로시저를 이용합니다. 그리고 인자를 사용하기 위해 SqlParameter 개체를 보관하는 컬렉션이 있으며 수행할 작업 종류에 따라 다양한 명령 방법을 제공하고 있습니다.

 

 SqlCommand 개체를 생성한 후에 작업 내용에 해당하는 쿼리 문자열 혹은 저장 프로시저를 CommandText속성에 설정하거나 생성할 때 입력 인자로 전달할 수 있습니다. 그리고 SqlCommand 개체를 이용하여 구체적인 작업을 수행하기 전에 연결이 열린 SqlConnection 개체를 지정해야 하는데 이 또한 생성자에 인자로 전달하거나 Connection 속성에 설정할 수 있습니다.

 

Program.cs


using System;

using System.Data.SqlClient;

 

namespace SqlCommand_개요

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                string constr = @"Data Source=516-41\SQLEXPRESS2;Initial Catalog=EHDB;Integrated Security=True;Pooling=False;";

                //516-41\SQLEXPRESS2 대신 실제 DBMS 인스턴스 명으로 변경하세요.

                //Catalog 대신 연결할 데이터 베이스 명으로 변경하세요.

                // 코드는 윈도우 계정으로 연결한 예제입니다.

                SqlConnection scon = new SqlConnection();

                scon.ConnectionString = constr;

                scon.Open(); //연결 열기

 

                ExSqlCommand(constr,"insert into Custom (CNAME, PHONE,ADDR) values('홍길동','010-1111-1234','서울시 종로구 종로1 1번지')" );

 

                scon.Close(); //연결 닫기

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        }

        private static void ExSqlCommand(string constr, string comstr)

        {

            SqlConnection scon = new SqlConnection(constr);

            SqlCommand scom = new SqlCommand();

            scom.CommandText = comstr;

            scom.Connection = scon;

            scon.Open();

            scom.ExecuteNonQuery();

            scon.Close();

        }

    }

}

 

클래스 상속 계층

System.Object

  System.MarshalByRefObject

    System.ComponentModel.Component

      System.Data.Common.DbCommand

        System.Data.SqlClient.SqlCommand

 

▷네임 스페이스 : System.Data.SqlCleint

▷어셈블리: System.Data.dll

반응형