DbConnection, DbCommand e DbException

Dopo aver creato un oggetto DbProviderFactory e un oggetto DbConnection, è possibile usare comandi e lettori di dati per recuperare i dati dall'origine dati.

Esempio di recupero di dati

In questo esempio viene usato un oggetto DbConnection come argomento. Viene creato un oggetto DbCommand per selezionare dati dalla tabella Categories impostando CommandText su un'istruzione SQL SELECT. Nel codice si presuppone che la tabella Categories esista nell'origine dati. La connessione viene aperta e i dati vengono recuperati tramite DbDataReader.

// Takes a DbConnection and creates a DbCommand to retrieve data
// from the Categories table by executing a DbDataReader.
static void DbCommandSelect(DbConnection connection)
{
    const 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.");
    }
}
' 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

Esempio di esecuzione di un comando

In questo esempio viene usato un oggetto DbConnection come argomento. Se DbConnection è valido, la connessione viene aperta e viene creato ed eseguito un oggetto DbCommand. CommandText viene impostato su un'istruzione SQL INSERT che esegue un inserimento nella tabella Categories del database Northwind. Nel codice si presuppone che il database Northwind esista nell'origine dati e che la sintassi SQL usata nell'istruzione INSERT sia valida per il provider specificato. Gli errori che si verificano nell'origine dati vengono gestiti dal blocco di codice DbException, mentre tutte le altre eccezioni vengono gestite nel blocco Exception.

// 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')";
                var 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.");
    }
}
' 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

Gestione di errori dei dati con DbException

La classe DbException è la classe di base per tutte le eccezioni generate per conto di un'origine dati. È possibile usarla nel codice di gestione delle eccezioni per gestire le eccezioni generate da provider diversi senza dover fare riferimento a una classe di eccezioni specifica. Nel frammento di codice seguente viene illustrato come usare DbException per visualizzare le informazioni sugli errori restituiti dall'origine dati tramite le proprietà GetType, Source, ErrorCode e Message. Nell'output verranno visualizzati il tipo di errore, l'origine indicante il nome del provider, un codice di errore e il messaggio associato all'errore.

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.  
}  

Vedi anche