Nyelv
Megjegyzés
Az oldalhoz való hozzáféréshez engedély szükséges. Megpróbálhat bejelentkezni vagy módosítani a címtárat.
Az oldalhoz való hozzáféréshez engedély szükséges. Megpróbálhatja módosítani a címtárat.
Miután létrehozott egy DbProviderFactory és egy DbConnection, parancsokkal és adatolvasókkal is lekérheti az adatokat az adatforrásból.
Példa adatlekérésre
Ez a példa egy DbConnection objektumot vesz fel argumentumként. Egy DbCommand jön létre, amely adatokat választ ki a Kategóriák táblából úgy, hogy a CommandText-et egy SQL SELECT utasításra állítják be. A kód feltételezi, hogy a Kategóriák tábla létezik az adatforrásban. A kapcsolat megnyílik, és az adatok lekérése egy DbDataReaderhasználatával történik.
// 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($"{reader[0]}. {reader[1]}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception.Message: {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
Példa parancs végrehajtására
Ez a példa egy DbConnection objektumot vesz fel argumentumként. Ha a DbConnection érvényes, a kapcsolat megnyílik, és létrejön és végrehajtásra kerül egy DbCommand. A CommandText egy SQL INSERT utasításra van állítva, amely beszúrja a Northwind-adatbázis Kategóriák táblájába. A kód feltételezi, hogy a Northwind-adatbázis létezik az adatforrásban, és hogy az INSERT utasításban használt SQL-szintaxis érvényes a megadott szolgáltatóra. Az adatforrásban előforduló hibákat a DbException kódblokk kezeli, a többi kivételt pedig a Exception blokk kezeli.
// 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 {rows} rows.");
}
// Handle data errors.
catch (DbException exDb)
{
Console.WriteLine($"DbException.GetType: {exDb.GetType()}");
Console.WriteLine($"DbException.Source: {exDb.Source}");
Console.WriteLine($"DbException.ErrorCode: {exDb.ErrorCode}");
Console.WriteLine($"DbException.Message: {exDb.Message}");
}
// Handle all other exceptions.
catch (Exception ex)
{
Console.WriteLine($"Exception.Message: {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
Adathibák kezelése a DbException használatával
A DbException osztály az adatforrás nevében kidobott összes kivétel alaposztálya. A kivételkezelési kódban használhatja a különböző szolgáltatók által kidobott kivételeket anélkül, hogy egy adott kivételosztályra kellene hivatkoznia. Az alábbi kódrészlet bemutatja, hogyan jeleníthetők meg DbException az adatforrás által visszaadott hibainformációk a GetType, Source, ErrorCodeés Message tulajdonságok használatával. A kimenet megjeleníti a hiba típusát, a szolgáltató nevét, egy hibakódot és a hibához társított üzenetet.
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.
}