명령 실행

.NET Framework에 포함된 각 .NET Framework 데이터 공급자에는 DbCommand에서 상속되는 고유 명령 개체가 있습니다. .NET Framework Data Provider for OLE DB에는 OleDbCommand 개체가 있고, .NET Framework Data Provider for SQL Server에는 SqlCommand 개체가 있으며, .NET Framework Data Provider for ODBC와 .NET Framework Data Provider for Oracle에는 각각 OdbcCommand 개체와 OracleCommand 개체가 있습니다. 이러한 각 개체는 명령의 유형 및 원하는 반환 값을 기준으로 명령 실행을 위한 메서드를 노출합니다. 다음 표에는 이러한 명령 및 해당 반환 값이 나와 있습니다.

명령 Return Value
ExecuteReader DataReader 개체를 반환합니다.
ExecuteScalar 단일 스칼라 값을 반환합니다.
ExecuteNonQuery 어떠한 행도 반환하지 않는 명령을 실행합니다.
ExecuteXMLReader XmlReader를 반환합니다. SqlCommand 개체에만 사용할 수 있습니다.

강력한 형식의 각 명령 개체는 명령 문자열의 해석 방법을 지정하는 CommandType 열거형도 지원합니다. 다음 표에는 CommandType의 각 열거형이 나와 있습니다.

CommandType 설명
Text 데이터 소스에 실행할 문을 정의하는 SQL 명령입니다.
StoredProcedure 저장 프로시저의 이름입니다. 호출하는 Parameters 메서드에 관계없이 명령의 Execute 속성을 사용하면 입력 및 출력 매개 변수와 반환 값에 액세스할 수 있습니다. ExecuteReader를 사용하는 경우 DataReader가 닫히기 전에는 반환 값과 출력 매개 변수에 액세스할 수 없습니다.
TableDirect 테이블의 이름입니다.

예시

다음 코드 예제에서는 SqlCommand 개체를 만든 다음 해당 속성을 설정하여 저장 프로시저를 실행하는 방법을 보여 줍니다. 저장 프로시저에 대한 입력 매개 변수를 지정하는 데는 SqlParameter 개체를 사용합니다. ExecuteReader 메서드를 사용하여 명령을 실행하고 SqlDataReader의 출력을 콘솔 창에 표시합니다.

static void GetSalesByCategory(string connectionString,
    string categoryName)
{
    using (SqlConnection connection = new(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new()
        {
            Connection = connection,
            CommandText = "SalesByCategory",
            CommandType = CommandType.StoredProcedure
        };

        // Add the input parameter and set its properties.
        SqlParameter parameter = new()
        {
            ParameterName = "@CategoryName",
            SqlDbType = SqlDbType.NVarChar,
            Direction = ParameterDirection.Input,
            Value = categoryName
        };

        // Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            reader.Close();
        }
    }
}
Shared Sub GetSalesByCategory(ByVal connectionString As String, _
    ByVal categoryName As String)

    Using connection As New SqlConnection(connectionString)

        ' Create the command and set its properties.
        Dim command As SqlCommand = New SqlCommand()
        command.Connection = connection
        command.CommandText = "SalesByCategory"
        command.CommandType = CommandType.StoredProcedure

        ' Add the input parameter and set its properties.
        Dim parameter As New SqlParameter()
        parameter.ParameterName = "@CategoryName"
        parameter.SqlDbType = SqlDbType.NVarChar
        parameter.Direction = ParameterDirection.Input
        parameter.Value = categoryName

        ' Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter)

        ' Open the connection and execute the reader.
        connection.Open()
        Using reader As SqlDataReader = command.ExecuteReader()

            If reader.HasRows Then
                Do While reader.Read()
                    Console.WriteLine("{0}: {1:C}", _
                      reader(0), reader(1))
                Loop
            Else
                Console.WriteLine("No rows returned.")
            End If
        End Using
    End Using
End Sub

명령 문제 해결

.NET Framework Data Provider for SQL Server는 실패한 명령 실행과 관련된 간헐적인 문제를 감지할 수 있도록 성능 카운터를 추가합니다. 자세한 내용은 성능 카운터를 참조하세요.

참고 항목