다음을 통해 공유


명령 실행

.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에는 OdbcCommand 개체가 포함되고, .NET Framework Data Provider for Oracle에는 OracleCommand 개체가 포함됩니다. 이러한 각 개체는 다음 표에 설명된 대로 명령 형식 및 원하는 반환 값에 따라 명령을 실행하는 메서드를 노출합니다.

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

강력한 형식의 각 명령 개체는 명령 문자열을 해석하는 방법을 지정하는 CommandType 열거형을 다음 표에 설명된 대로 지원합니다.

명령 유형 설명
Text 데이터 원본에서 실행할 문을 정의하는 SQL 명령입니다.
StoredProcedure 저장 프로시저의 이름입니다. 어떤 메서드가 호출되든 관계없이 명령의 Parameters 속성을 사용하여 입력 및 출력 매개 변수에 액세스하고 값을 반환받을 수도 있습니다. 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($"{reader[0]}: {reader[1]:C}");
                }
            }
            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는 실패한 명령 실행과 관련된 일시적인 문제를 감지할 수 있도록 성능 카운터를 추가합니다. 자세한 내용은 성능 카운터를 참조하세요.

참고하십시오