When using Update, the order of execution is as follows:
- The values in the DataRow are moved to the parameter values.
- The OnRowUpdating event is raised.
- The command executes.
- If the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.
- If there are output parameters, they are placed in the DataRow.
- The OnRowUpdated event is raised.
- AcceptChanges is called.
Detached | 행을 만들었지만 이 행은 DataRowCollection의 일부가 아닙니다. DataRow는 만들어진 직후 및 컬렉션에 추가되기 전 또는 컬렉션에서 제거된 경우 이 상태가 됩니다. | |
Unchanged | AcceptChanges를 마지막으로 호출한 이후 행이 변경되지 않았습니다. | |
Added | 행이 DataRowCollection에 추가되었으며 AcceptChanges는 호출되지 않았습니다. | |
Deleted | DataRow의 Delete 메서드를 사용하여 행을 삭제했습니다. | |
Modified | 행이 수정되었으며 AcceptChanges는 호출되지 않 |
Private Sub DemonstrateRowState() 'Run a function to create a DataTable with one column. Dim dataTable As DataTable = MakeTable() Dim dataRow As DataRow ' Create a new DataRow. dataRow = dataTable.NewRow() ' Detached row. Console.WriteLine(String.Format("New Row {0}", dataRow.RowState)) dataTable.Rows.Add(dataRow) ' New row. Console.WriteLine(String.Format("AddRow {0}", dataRow.RowState)) dataTable.AcceptChanges() ' Unchanged row. Console.WriteLine(String.Format("AcceptChanges {0}", dataRow.RowState)) dataRow("FirstName") = "Scott" ' Modified row. Console.WriteLine(String.Format("Modified {0}", dataRow.RowState)) dataRow.Delete() ' Deleted row. Console.WriteLine(String.Format("Deleted {0}", dataRow.RowState)) End Sub Private Function MakeTable() As DataTable ' Make a simple table with one column. Dim dt As New DataTable("dataTable") Dim firstName As New DataColumn("FirstName", _ Type.GetType("System.String")) dt.Columns.Add(firstName) Return dt End Function
Original | The row contains its original values. | |
Current | The row contains current values. | |
Proposed | The row contains a proposed value. | |
Default | The default version of DataRowState. For a DataRowState value of Added,Modified or Deleted, the default version is Current. For a DataRowState value ofDetached, the version is Proposed. |
Private Sub DemonstrateRowState() 'Run a function to create a DataTable with one column. Dim dataTable As DataTable = MakeTable() Dim dataRow As DataRow ' Create a new DataRow. dataRow = dataTable.NewRow() ' Detached row. Console.WriteLine(String.Format("New Row {0}", dataRow.RowState)) dataTable.Rows.Add(dataRow) ' New row. Console.WriteLine(String.Format("AddRow {0}", dataRow.RowState)) dataTable.AcceptChanges() ' Unchanged row. Console.WriteLine(String.Format("AcceptChanges {0}", dataRow.RowState)) dataRow("FirstName") = "Scott" ' Modified row. Console.WriteLine(String.Format("Modified {0}", dataRow.RowState)) dataRow.Delete() ' Deleted row. Console.WriteLine(String.Format("Deleted {0}", dataRow.RowState)) End Sub Private Function MakeTable() As DataTable ' Make a simple table with one column. Dim dt As New DataTable("dataTable") Dim firstName As New DataColumn("FirstName", _ Type.GetType("System.String")) dt.Columns.Add(firstName) Return dt End Function
reate table TestTable (id int primary key, fname nvarchar(50), lname nvarchar(50))
insert into TestTable values (1, 'Mike', 'Spike')
insert into TestTable values (2, 'John', 'Johnson')
insert into TestTable values (3, 'Pete', 'Peterson')
--drop table TestTable
Then create a new C# Console application and run the following code:
static void Main(string[] args)
{
string cs = @"Data Source=<your server>;Initial Catalog=<your database>;Integrated Security=SSPI";
string sql = "SELECT id, fname, lname FROM TestTable";
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable("Persons");
da.Fill(dt);
Console.WriteLine("Rows are untouched...");
ViewDataTableRowStatus(dt);
// Modify a row.
Console.WriteLine("Modifying the first row...");
dt.Rows[0][1] = "Jake";
ViewDataTableRowStatus(dt);
// Add a row.
Console.WriteLine("Adding a row");
dt.Rows.Add(new object[]{100, "Paul", "Paulson..."});
ViewDataTableRowStatus(dt);
// Now, if calling AcceptChanges() all rows will be set to Unchanged.
Console.WriteLine("Calling AcceptChanges()...");
dt.AcceptChanges();
ViewDataTableRowStatus(dt);
// This means that when we call update on the DataAdapter, it will return 0
// since no rows has actuall been sent to the database. (first we need to build the INSERT and UPDATE commands)
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.InsertCommand = builder.GetInsertCommand();
da.UpdateCommand = builder.GetUpdateCommand();
int rows = da.Update(dt);
Console.WriteLine("Updated rows: {0}", rows);
}
}
private static void ViewDataTableRowStatus(DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
Console.WriteLine("Id:{0}\tFirstName: {1}\tRowState: {2}", dr[0].ToString(), dr[1].ToString(), dr.RowState.ToString());
}
Console.WriteLine();
}
이전 버전의 ADO.NET에서는 데이터베이스를 DataSet의 변경 내용으로 업데이트하는 경우 DataAdapter의 Update 메서드에서 데이터베이스에 대해 한 번에 한 행씩 업데이트를 수행했습니다. 또한 지정한DataTable의 행에서 반복될 때 수정되었는지 여부를 확인하기 위해 각 DataRow를 검사했습니다. 행이 수정된 경우에는 해당 행의 RowState 속성 값에 따라 적절한 UpdateCommand, InsertCommand또는 DeleteCommand를 호출했습니다. 그리고 행을 업데이트할 때마다 데이터베이스에 대한 네트워크 라운드트립이 수반되었습니다.
그러나 ADO.NET 2.0에서는 DataAdapter가 UpdateBatchSize 속성을 노출합니다. UpdateBatchSize를 양의 정수 값으로 설정하면 데이터베이스가 업데이트되어 지정된 크기의 배치로 전송됩니다. For example, setting the UpdateBatchSize to 10 will group 10 separate statements and submit them as single batch. UpdateBatchSize를 0으로 설정하면 DataAdapter가 서버에서 처리할 수 있는 최대 배치 크기를 사용합니다. 1로 설정할 경우에는 행이 한 번에 하나씩 전송되므로 배치 업데이트를 사용할 수 없습니다.
너무 큰 배치를 실행하면 성능이 저하될 수 있습니다. 따라서 응용 프로그램을 구현하기 전에 최적의 배치 크기 설정을 테스트해야 합니다.
UpdateBatchSize 속성 사용
When batch updates are enabled, the UpdatedRowSource property value of the DataAdapter's UpdateCommand, InsertCommand, and DeleteCommand should be set to None orOutputParameters. 배치 업데이트를 수행하는 경우 명령의 UpdatedRowSource 속성 값 FirstReturnedRecord 또는 Both는 유효하지 않습니다.
다음 프로시저에서는 UpdateBatchSize 속성을 사용하는 방법을 보여 줍니다. 이 프로시저에서는 Production.ProductCategory 테이블의 ProductCategoryID 및 Name 필드를 표시하는 열이 포함된DataSet 개체와 배치 크기를 나타내는 정수(배치의 행 개수) 등 두 가지 인수를 사용합니다. 이 코드에서는 UpdateCommand, InsertCommand 및 DeleteCommand 속성을 설정하여 새 SqlDataAdapter 개체를 만듭니다. 또한 DataSet 개체에 수정된 행이 있다고 가정합니다. 그리고 UpdateBatchSize 속성을 설정한 다음 업데이트를 실행합니다.
Public Sub BatchUpdate( _ ByVal dataTable As DataTable, ByVal batchSize As Int32) ' Assumes GetConnectionString() returns a valid connection string. Dim connectionString As String = GetConnectionString() ' Connect to the AdventureWorks database. Using connection As New SqlConnection(connectionString) ' Create a SqlDataAdapter. Dim adapter As New SqlDataAdapter() 'Set the UPDATE command and parameters. adapter.UpdateCommand = New SqlCommand( _ "UPDATE Production.ProductCategory SET " _ & "Name=@Name WHERE ProductCategoryID=@ProdCatID;", _ connection) adapter.UpdateCommand.Parameters.Add("@Name", _ SqlDbType.NVarChar, 50, "Name") adapter.UpdateCommand.Parameters.Add("@ProdCatID", _ SqlDbType.Int, 4, " ProductCategoryID ") adapter.UpdateCommand.UpdatedRowSource = _ UpdateRowSource.None 'Set the INSERT command and parameter. adapter.InsertCommand = New SqlCommand( _ "INSERT INTO Production.ProductCategory (Name) VALUES (@Name);", _ connection) adapter.InsertCommand.Parameters.Add("@Name", _ SqlDbType.NVarChar, 50, "Name") adapter.InsertCommand.UpdatedRowSource = _ UpdateRowSource.None 'Set the DELETE command and parameter. adapter.DeleteCommand = New SqlCommand( _ "DELETE FROM Production.ProductCategory " _ & "WHERE ProductCategoryID=@ProdCatID;", connection) adapter.DeleteCommand.Parameters.Add("@ProdCatID", _ SqlDbType.Int, 4, " ProductCategoryID ") adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None ' Set the batch size. adapter.UpdateBatchSize = batchSize ' Execute the update. adapter.Update(dataTable) End Using End Sub
DataAdapter에는 업데이트 관련 이벤트인 RowUpdating 및 RowUpdated가 있습니다. 이전 버전의 ADO.NET에서 일괄 처리가 비활성화되어 있는 경우 각 이벤트는 처리되는 각 행마다 생성됩니다.RowUpdating은 업데이트가 발생하기 전에 생성되며 RowUpdated는 데이터베이스 업데이트가 완료된 뒤에 생성됩니다.
배치 업데이트에 따른 이벤트 동작 변경
일괄 처리가 활성화되면 한 번의 데이터베이스 동작으로 여러 개의 행이 업데이트됩니다. 따라서 RowUpdated 이벤트는 배치마다 한 번씩만 발생하지만 RowUpdating 이벤트는 행이 처리될 때마다 발생합니다. 일괄 처리가 비활성화되면 일대일 인터리빙으로 두 개의 이벤트가 발생합니다. 이 경우 RowUpdating 이벤트 하나와 RowUpdated 이벤트 하나가 한 행에 대해 발생한 후 모든 행이 처리될 때까지RowUpdating 및 RowUpdated 이벤트가 다음 행에 대해 하나씩 발생합니다.
업데이트된 행 액세스
일괄 처리가 비활성화되면 RowUpdatedEventArgs 클래스의 Row 속성을 사용하여 업데이트되는 행에 액세스할 수 있습니다.
일괄 처리가 활성화되면 여러 행에 대해 하나의 RowUpdated 이벤트가 생성됩니다. 따라서 각 행에 대한 Row 속성 값은 null입니다. RowUpdating 이벤트는 계속해서 각 행에 대해 생성됩니다.RowUpdatedEventArgs 클래스의 CopyToRows 메서드를 사용하면 행에 대한 참조를 배열에 복사하여 처리된 행에 액세스할 수 있습니다. 처리 중인 행이 없으면 CopyToRows에서ArgumentNullException이 throw됩니다. CopyToRows 메서드를 호출하기 전에 RowCount 속성을 사용하여 처리된 행 수를 반환합니다.