DbConnection, DbCommand 및 DbException
DbProviderFactory 및 DbConnection만든 후에는 명령 및 데이터 판독기를 사용하여 데이터 원본에서 데이터를 검색할 수 있습니다.
데이터 검색 예제
이 예제에서는 DbConnection
개체를 인수로 사용합니다.
CommandText을 SQL SELECT 문으로 설정하여 Categories 테이블에서 데이터를 선택하기 위한 DbCommand가 생성됩니다. 코드는 범주 테이블이 데이터 원본에 있다고 가정합니다. 네트워크 연결이 열리고 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($"{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
명령 예제 실행
이 예제에서는 DbConnection
개체를 인수로 사용합니다.
DbConnection
유효한 경우 연결이 열리고 DbCommand 만들어지고 실행됩니다.
CommandText Northwind 데이터베이스의 Categories 테이블에 삽입을 수행하는 SQL INSERT 문으로 설정됩니다. 이 코드는 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 {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
DbException을 사용하여 데이터 오류 처리
DbException 클래스는 데이터 원본을 대신하여 throw된 모든 예외에 대한 기본 클래스입니다. 예외 처리 코드에서 이를 사용하여 특정 예외 클래스를 참조하지 않고도 다른 공급자가 throw한 예외를 처리할 수 있습니다. 다음 코드 조각에서는 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.
}
참고하십시오
- DbProviderFactories
- DbProviderFactory 가져오기
- DbDataAdapter 사용하여 데이터 수정
- ADO.NET 개요