ADO.NET DataAdapter 데이터 원본의 데이터 변경 내용에 응답하는 데 사용할 수 있는 세 가지 이벤트를 노출합니다. 다음 표는 DataAdapter
이벤트를 보여 줍니다.
이벤트 | 설명 |
---|---|
RowUpdating |
메서드 중 하나를 Update 호출하여 행에 대한 UPDATE, INSERT 또는 DELETE 작업이 시작됩니다. |
RowUpdated |
메서드 중 하나를 Update 호출하여 행에 대한 UPDATE, INSERT 또는 DELETE 작업이 완료되었습니다. |
FillError |
작업 중에 Fill 오류가 발생했습니다. |
RowUpdating 및 RowUpdated
RowUpdating
는 데이터 원본에서 DataSet의 행이 업데이트되기 전에 발생합니다.
RowUpdated
는 행에 대한 DataSet
의 업데이트가 데이터 원본에서 처리된 후에 발생합니다. 따라서 업데이트 동작이 발생하기 전에 수정하고, 업데이트가 발생할 때 추가 처리를 제공하고, 업데이트된 행에 대한 참조를 유지하고, 현재 업데이트를 취소하고, 나중에 처리할 일괄 처리 프로세스를 예약하는 데 사용할 RowUpdating
수 있습니다.
RowUpdated
는 업데이트 중에 발생하는 오류 및 예외에 응답하는 데 유용합니다. 오류 정보를 DataSet
에 추가할 수 있으며, 재시도 논리 등을 포함할 수 있습니다.
RowUpdatingEventArgs 인수와 RowUpdatedEventArgs 인수는 RowUpdating
및 RowUpdated
이벤트에 전달되며 다음을 포함합니다: 업데이트를 수행하는 데 사용되는 Command
객체를 참조하는 Command
속성, 업데이트된 정보를 포함하는 Row
객체를 참조하는 DataRow
속성, 수행 중인 업데이트 유형을 나타내는 StatementType
속성, 해당하는 경우 TableMapping
, 그리고 작업의 Status
.
이 속성을 사용하여 Status
작업 중에 오류가 발생했는지 확인하고 원하는 경우 현재 및 결과 행에 대한 작업을 제어할 수 있습니다. 이벤트가 발생하면 Status
속성은 Continue
또는 ErrorsOccurred
입니다. 다음 표는 업데이트 중에 이후 작업을 제어하기 위해 Status
속성으로 설정할 수 있는 값을 보여 줍니다.
상태 | 설명 |
---|---|
Continue |
업데이트 작업을 계속합니다. |
ErrorsOccurred |
업데이트 작업을 중단하고 예외를 발생시킵니다. |
SkipCurrentRow |
현재 행을 무시하고 업데이트 작업을 계속합니다. |
SkipAllRemainingRows |
업데이트 작업을 중단하지만 예외를 던지지는 않습니다. |
Status
속성을 설정하면 예외가 발생합니다.
Errors
속성을 원하는 예외로 설정하여 해당 예외가 throw되도록 제어할 수 있습니다. 다른 값 Status
중 하나를 사용하면 예외가 발생하지 않도록 합니다.
이 속성을 사용하여 업데이트된 ContinueUpdateOnError
행에 대한 오류를 처리할 수도 있습니다.
DataAdapter.ContinueUpdateOnError
이 true
일 경우, 행 업데이트로 인해 예외가 발생하면, 예외 텍스트가 해당 행의 RowError
정보에 배치되고, 예외를 발생시키지 않고 처리가 계속됩니다. 오류가 발생할 때 응답할 수 있도록 해주는 Update
이벤트와는 달리, RowUpdated
이 완료될 때 오류에 응답할 수 있습니다.
다음 코드 샘플에서는 이벤트 처리기를 추가 및 제거하는 방법을 보여 줍니다.
RowUpdating
이벤트 처리기는 타임스탬프를 사용하여 삭제된 모든 레코드의 로그를 씁니다.
RowUpdated
이벤트 처리기는 행의 속성에 RowError
오류 정보를 DataSet
추가하고 예외를 표시하지 않으며 처리를 계속합니다(동작 ContinueUpdateOnError
= true
미러링).
' Assumes that connection is a valid SqlConnection object.
Dim custAdapter As SqlDataAdapter = New SqlDataAdapter( _
"SELECT CustomerID, CompanyName FROM Customers", connection)
' Add handlers.
AddHandler custAdapter.RowUpdating, New SqlRowUpdatingEventHandler( _
AddressOf OnRowUpdating)
AddHandler custAdapter.RowUpdated, New SqlRowUpdatedEventHandler(
AddressOf OnRowUpdated)
' Set DataAdapter command properties, fill DataSet, and modify DataSet.
custAdapter.Update(custDS, "Customers")
' Remove handlers.
RemoveHandler custAdapter.RowUpdating, _
New SqlRowUpdatingEventHandler(AddressOf OnRowUpdating)
RemoveHandler custAdapter.RowUpdated, _
New SqlRowUpdatedEventHandler(AddressOf OnRowUpdated)
Private Shared Sub OnRowUpdating(sender As Object, _
args As SqlRowUpdatingEventArgs)
If args.StatementType = StatementType.Delete Then
Dim tw As System.IO.TextWriter = _
System.IO.File.AppendText("Deletes.log")
tw.WriteLine( _
"{0}: Customer {1} Deleted.", DateTime.Now, args.Row(_
"CustomerID", DataRowVersion.Original))
tw.Close()
End If
End Sub
Private Shared Sub OnRowUpdated( _
sender As Object, args As SqlRowUpdatedEventArgs)
If args.Status = UpdateStatus.ErrorsOccurred
args.Status = UpdateStatus.SkipCurrentRow
args.Row.RowError = args.Errors.Message
End If
End Sub
// Assumes that connection is a valid SqlConnection object.
SqlDataAdapter custAdapter = new SqlDataAdapter(
"SELECT CustomerID, CompanyName FROM Customers", connection);
// Add handlers.
custAdapter.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating);
custAdapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
// Set DataAdapter command properties, fill DataSet, modify DataSet.
custAdapter.Update(custDS, "Customers");
// Remove handlers.
custAdapter.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating);
custAdapter.RowUpdated -= new SqlRowUpdatedEventHandler(OnRowUpdated);
protected static void OnRowUpdating(
object sender, SqlRowUpdatingEventArgs args)
{
if (args.StatementType == StatementType.Delete)
{
System.IO.TextWriter tw = System.IO.File.AppendText("Deletes.log");
tw.WriteLine(
"{0}: Customer {1} Deleted.", DateTime.Now,
args.Row["CustomerID", DataRowVersion.Original]);
tw.Close();
}
}
protected static void OnRowUpdated(
object sender, SqlRowUpdatedEventArgs args)
{
if (args.Status == UpdateStatus.ErrorsOccurred)
{
args.Row.RowError = args.Errors.Message;
args.Status = UpdateStatus.SkipCurrentRow;
}
}
채우기 오류
DataAdapter
작업 중에 오류가 발생하면 FillError
작업에서 Fill
이벤트가 발생합니다. 이 유형의 오류는 추가되는 행의 데이터를 정밀도의 일부 손실 없이 .NET Framework 형식으로 변환할 수 없는 경우에 일반적으로 발생합니다.
작업 중에 Fill
오류가 발생하면 현재 행이 DataTable
에 추가되지 않습니다. 이 FillError
이벤트를 사용하면 오류를 해결하고 행을 추가하거나 제외된 행을 무시하고 작업을 계속할 수 Fill
있습니다.
FillErrorEventArgs
는 FillError
이벤트에 전달될 때, 오류에 응답하고 해결할 수 있는 여러 속성을 포함할 수 있습니다. 다음 표에서는 개체의 FillErrorEventArgs
속성을 보여줍니다.
재산 | 설명 |
---|---|
Errors |
Exception 가 발생한 것입니다. |
DataTable |
오류 발생 시 채워지는 DataTable 개체입니다. |
Values |
오류가 발생했을 때 추가되는 행의 값을 포함하는 개체의 배열입니다. 배열의 Values 서수 참조는 추가되는 행 열의 서수 참조에 해당합니다. 예를 들어 Values[0] 행의 첫 번째 열로 추가된 값입니다. |
Continue |
예외를 던질지 여부를 선택할 수 있습니다.
Continue 속성을 false 로 설정하면 현재 Fill 작업이 중지되고 예외가 발생합니다.
Continue 을(를) true 으로 설정하면 오류에도 불구하고 Fill 작업이 계속 진행됩니다. |
다음 코드 예제에서는 FillError
이벤트의 이벤트 처리기를 DataAdapter
에 추가합니다.
FillError
이벤트 코드에서, 예제는 정밀도 손실 가능성이 있는지 확인하여 예외에 대응할 수 있는 기회를 제공합니다.
AddHandler adapter.FillError, New FillErrorEventHandler( _
AddressOf FillError)
Dim dataSet As DataSet = New DataSet
adapter.Fill(dataSet, "ThisTable")
Private Shared Sub FillError(sender As Object, _
args As FillErrorEventArgs)
If args.Errors.GetType() Is Type.GetType("System.OverflowException") Then
' Code to handle precision loss.
' Add a row to table using the values from the first two columns.
DataRow myRow = args.DataTable.Rows.Add(New Object() _
{args.Values(0), args.Values(1), DBNull.Value})
' Set the RowError containing the value for the third column.
myRow.RowError = _
"OverflowException encountered. Value from data source: " & _
args.Values(2)
args.Continue = True
End If
End Sub
adapter.FillError += new FillErrorEventHandler(FillError);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "ThisTable");
protected static void FillError(object sender, FillErrorEventArgs args)
{
if (args.Errors.GetType() == typeof(System.OverflowException))
{
// Code to handle precision loss.
//Add a row to table using the values from the first two columns.
DataRow myRow = args.DataTable.Rows.Add(new object[]
{args.Values[0], args.Values[1], DBNull.Value});
//Set the RowError containing the value for the third column.
myRow.RowError =
"OverflowException Encountered. Value from data source: " +
args.Values[2];
args.Continue = true;
}
}