次の方法で共有


DbConnection、DbCommand、および DbException (ADO.NET)

DbProviderFactory および DbConnection を作成すると、コマンドおよびデータ リーダーを使用してデータ ソースからデータを取得できます。

データの取得例

次のコード例は、DbConnection オブジェクトを引数として受け取ります。 CommandText に SQL SELECT ステートメントを設定することによって、Categories テーブルからデータを検索するための DbCommand を作成します。 このコードを実行するには、データ ソースに Categories テーブルが存在する必要があります。 接続を開いた後、DbDataReader を使用してデータが取得されます。

' Takes a DbConnection and creates a DbCommand to retrieve data
' from the Categories table by executing a DbDataReader. 
Private Shared Sub DbCommandSelect(ByVal connection As DbConnection)

    Dim queryString As String = _
       "SELECT CategoryID, CategoryName FROM Categories"

    ' Check for valid DbConnection.
    If Not connection Is Nothing Then
        Using connection
            Try
                ' Create the command.
                Dim command As DbCommand = connection.CreateCommand()
                command.CommandText = queryString
                command.CommandType = CommandType.Text

                ' Open the connection.
                connection.Open()

                ' Retrieve the data.
                Dim reader As DbDataReader = command.ExecuteReader()
                Do While reader.Read()
                    Console.WriteLine("{0}. {1}", reader(0), reader(1))
                Loop

            Catch ex As Exception
                Console.WriteLine("Exception.Message: {0}", ex.Message)
            End Try
        End Using
    Else
        Console.WriteLine("Failed: DbConnection is Nothing.")
    End If
End Sub
// Takes a DbConnection and creates a DbCommand to retrieve data
// from the Categories table by executing a DbDataReader. 
static void DbCommandSelect(DbConnection connection)
{
    string queryString =
        "SELECT CategoryID, CategoryName FROM Categories";

    // Check for valid DbConnection.
    if (connection != null)
    {
        using (connection)
        {
            try
            {
                // Create the command.
                DbCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                command.CommandType = CommandType.Text;

                // Open the connection.
                connection.Open();

                // Retrieve the data.
                DbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("{0}. {1}", reader[0], reader[1]);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception.Message: {0}", ex.Message);
            }
        }
    }
    else
    {
        Console.WriteLine("Failed: DbConnection is null.");
    }
}

コマンド実行例

次のコード例は、DbConnection オブジェクトを引数として受け取ります。 DbConnection が有効である場合、接続が開かれ、DbCommand が作成されて実行されます。 CommandText には、Northwind データベースの Categories テーブルへの挿入操作を実行する SQL INSERT ステートメントが設定されています。 このコードを実行するには、データ ソースに Northwind データベースが存在すること、および、指定されたプロバイダーの有効な SQL 構文が INSERT ステートメントに使用されていることが必要です。 データ ソースで発生したエラーは DbException コード ブロックで処理され、それ以外のすべての例外は Exception ブロックで処理されます。

' Takes a DbConnection and executes an INSERT statement.
' Assumes SQL INSERT syntax is supported by provider.
Private Shared Sub ExecuteDbCommand(ByVal connection As DbConnection)

    ' Check for valid DbConnection object.
    If Not connection Is Nothing Then
        Using connection
            Try
                ' Open the connection.
                connection.Open()

                ' Create and execute the DbCommand.
                Dim command As DbCommand = connection.CreateCommand()
                command.CommandText = _
                  "INSERT INTO Categories (CategoryName) VALUES ('Low Carb')"
                Dim rows As Integer = command.ExecuteNonQuery()

                ' Display number of rows inserted.
                Console.WriteLine("Inserted {0} rows.", rows)

            ' Handle data errors.
            Catch exDb As DbException
                Console.WriteLine("DbException.GetType: {0}", exDb.GetType())
                Console.WriteLine("DbException.Source: {0}", exDb.Source)
                Console.WriteLine("DbException.ErrorCode: {0}", exDb.ErrorCode)
                Console.WriteLine("DbException.Message: {0}", exDb.Message)

            ' Handle all other exceptions.
            Catch ex As Exception
                Console.WriteLine("Exception.Message: {0}", ex.Message)
            End Try
        End Using
    Else
        Console.WriteLine("Failed: DbConnection is Nothing.")
    End If
End Sub
// Takes a DbConnection, creates and executes a DbCommand. 
// Assumes SQL INSERT syntax is supported by provider.
static void ExecuteDbCommand(DbConnection connection)
{
    // Check for valid DbConnection object.
    if (connection != null)
    {
        using (connection)
        {
            try
            {
                // Open the connection.
                connection.Open();

                // Create and execute the DbCommand.
                DbCommand command = connection.CreateCommand();
                command.CommandText =
                    "INSERT INTO Categories (CategoryName) VALUES ('Low Carb')";
                int rows = command.ExecuteNonQuery();

                // Display number of rows inserted.
                Console.WriteLine("Inserted {0} rows.", rows);
            }
                // Handle data errors.
            catch (DbException exDb)
            {
                Console.WriteLine("DbException.GetType: {0}", exDb.GetType());
                Console.WriteLine("DbException.Source: {0}", exDb.Source);
                Console.WriteLine("DbException.ErrorCode: {0}", exDb.ErrorCode);
                Console.WriteLine("DbException.Message: {0}", exDb.Message);
            }
                // Handle all other exceptions.
            catch (Exception ex)
            {
                Console.WriteLine("Exception.Message: {0}", ex.Message);
            }
        }
    }
    else
    {
        Console.WriteLine("Failed: DbConnection is null.");
    }
}

DbException でのデータ エラーの処理

DbException クラスは、データ ソースでスローされるすべての例外の基本クラスです。 このクラスを例外処理コードに使用することで、プロバイダーに固有の例外クラスを参照することなく、各種のプロバイダーによってスローされる例外を処理できます。 次のコード フラグメントでは、DbException の各プロパティ (GetTypeSourceErrorCode、および Message) を使って、データ ソースから返されたエラー情報を表示しています。 出力結果には、エラーの種類、エラーの発生元 (プロバイダー名)、エラー コード、および、エラーに関連付けられたメッセージが表示されます。

    Try
        ' Do work here.
    Catch ex As DbException
        ' Display information about the exception.
        Console.WriteLine("GetType: {0}", ex.GetType())
        Console.WriteLine("Source: {0}", ex.Source)
        Console.WriteLine("ErrorCode: {0}", ex.ErrorCode)
        Console.WriteLine("Message: {0}", ex.Message)
    Finally
        ' Perform cleanup here.
    End Try
    try
    {
        // Do work here.
    }
    catch (DbException ex)
    {
        // Display information about the exception.
        Console.WriteLine("GetType: {0}", ex.GetType());
        Console.WriteLine("Source: {0}", ex.Source);
        Console.WriteLine("ErrorCode: {0}", ex.ErrorCode);
        Console.WriteLine("Message: {0}", ex.Message);
    }
    finally
    {
        // Perform cleanup here.
    }

参照

概念

DbProviderFactories (ADO.NET)

DbProviderFactory の取得 (ADO.NET)

DbDataAdapter を使用したデータの変更 (ADO.NET)