DbConnection、DbCommand 和 DbException
创建了 DbProviderFactory 和 DbConnection 后,您便可以使用命令和数据读取器来从数据源检索数据。
检索数据示例
此示例将 DbConnection
对象用作参数。 通过将 DbCommand 设置为 SQL SELECT 语句,可创建 CommandText 以从类别表中选择数据。 该代码假定数据源中存在类别表。 打开连接并使用 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
执行命令示例
此示例将 DbConnection
对象用作参数。 如果 DbConnection
有效,则会打开该连接,并创建和执行 DbCommand。 将 CommandText 设置为 SQL INSERT 语句,以执行插入到 Northwind 数据库类别表中的操作。 该代码假定数据源中存在 Northwind 数据库,并且 INSERT 语句中使用的 SQL 语法对于指定提供程序有效。 数据源中发生的错误由 DbException 代码块处理,其他所有异常在 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
使用 DbException 处理数据错误
DbException 类是代表数据源引发的所有异常的基类。 你可以在异常处理代码中使用该类来处理由各种提供程序引发的异常,而不必引用特定异常类。 下面的代码段演示如何使用 DbException 来显示使用 GetType、Source、ErrorCode 和 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.
}