コマンドの実行 (ADO.NET)

.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 列挙値をサポートしています。これらの列挙値を使用してコマンド文字列の解釈方法を指定できます。

CommandType

説明

Text

データ ソース側で実行されるステートメントを定義する SQL コマンド。

StoredProcedure

ストアド プロシージャの名前。 呼び出す Execute メソッドに関係なく、コマンドの Parameters プロパティを使用して入力パラメーターと出力パラメーターにアクセスし、戻り値を取得できます。 ExecuteReader を使用した場合は、DataReader を閉じるまで戻り値および出力パラメーターにアクセスすることはできません。

TableDirect

テーブルの名前。

SqlCommand オブジェクトを作成し、そのプロパティを設定することによってストアド プロシージャを実行するコード サンプルを次に示します。 ストアド プロシージャへの入力パラメーターは、SqlParameter オブジェクトを使って指定します。 このコマンドを ExecuteReader メソッドで実行し、SqlDataReader からの出力をコンソール ウィンドウに表示します。

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()
        Dim 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 Sub
static void GetSalesByCategory(string connectionString, 
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = 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();
        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();
    }
}

コマンドのトラブルシューティング

.NET Framework Data Provider for SQL Server には、失敗したコマンド実行に関連して断続的に発生する問題を検出できるパフォーマンス カウンターが追加されています。 詳細については、「パフォーマンス カウンター (ADO.NET)」を参照してください。

参照

その他の技術情報

コマンドとパラメーター (ADO.NET)

DataAdapter と DataReader (ADO.NET)

Working with DataReaders