Escolar Documentos
Profissional Documentos
Cultura Documentos
net
OleDbDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.OleDb namespace. OleDbDataAdapter provides the communication between the Dataset and the OleDb Data Sources. We can use OleDbDataAdapter Object in combination with Dataset Object. The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access and Data Manipulation operations in the OleDb Data Sources. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the OleDbDataAdapter.
Description Initializes a new instance of the OleDbDataAdapter class. Initializes a new instance of the OleDbDataAdapter class with the specified OleDbCommand as the SelectCommandproperty. Initializes a new instance of the OleDbDataAdapter class with a SelectCommand. Initializes a new instance of the OleDbDataAdapter class with a SelectCommand.
Properties
Name AcceptChangesDuringFill
Description Gets or sets a value indicating whether AcceptChanges is called on aDataRow after it is added to the DataTable during any of the Filloperations. (Inherited from DataAdapter.)
AcceptChangesDuringUpdate Gets or sets whether AcceptChanges is called during a Update.(Inherited from DataAdapter.) CanRaiseEvents Gets a value indicating whether the component can raise an event.(Inherited from Component.) Gets the IContainer that contains the Component. (Inherited fromComponent.) Gets or sets a value that specifies whether to generate an exception when an error is encountered during a row update. (Inherited fromDataAdapter.) Gets or sets an SQL statement or stored procedure for deleting records from the data set. Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component.(Inherited from Component.) Gets or sets the behavior of the command used to fill the data adapter. (Inherited from DbDataAdapter.) Gets or sets the LoadOption that determines how the adapter fills theDataTable from the DbDataReader. (Inherited from DataAdapter.) Gets or sets an SQL statement or stored procedure used to insert new records into the data source. Determines the action to take when incoming data does not have a matching table or column. (Inherited from DataAdapter.) Determines the action to take when existing DataSet schema does not match incoming data. (Inherited from DataAdapter.) Gets or sets whether the Fill method should return provider-specific values or common CLS-compliant values. (Inherited fromDataAdapter.) Gets or sets an SQL statement or stored procedure used to select records in the data source. Gets or sets the ISite of the Component. (Inherited from Component.)
Container
ContinueUpdateOnError
DeleteCommand
DesignMode
Events
FillCommandBehavior
FillLoadOption
InsertCommand
MissingMappingAction
MissingSchemaAction
ReturnProviderSpecificTypes
SelectCommand
Site
TableMappings
Gets a collection that provides the master mapping between a source table and a DataTable. (Inherited from DataAdapter.) Gets or sets a value that enables or disables batch processing support, and specifies the number of commands that can be executed in a batch. (Inherited from DbDataAdapter.) Gets or sets an SQL statement or stored procedure used to update records in the data source.
UpdateBatchSize
UpdateCommand Methods
Name AddToBatch
Description Adds a IDbCommand to the current batch. (Inherited fromDbDataAdapter.) Removes all IDbCommand objects from the batch.(Inherited from DbDataAdapter.) Obsolete. Creates a copy of this instance of DataAdapter.(Inherited from DataAdapter.) Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Initializes a new instance of the RowUpdatedEventArgsclass. (Inherited from DbDataAdapter.) Initializes a new instance of the RowUpdatingEventArgsclass. (Inherited from DbDataAdapter.) Creates a new DataTableMappingCollection. (Inherited fromDataAdapter.) Releases all resources used by the Component. (Inherited from Component.) Releases the unmanaged resources used by theDbDataAdapter and optionally releases the managed resources. (Inherited from DbDataAdapter.) Determines whether the specified Object is equal to the
ClearBatch
CloneInternals
CreateObjRef
CreateRowUpdatedEvent
CreateRowUpdatingEvent
CreateTableMappings
Dispose
Dispose(Boolean)
Equals(Object)
current Object. (Inherited from Object.) ExecuteBatch Fill(DataSet) Executes the current batch. (Inherited from DbDataAdapter.) Adds or refreshes rows in the DataSet. (Inherited fromDbDataAdapter.) Adds or refreshes rows in a specified range in the DataSetto match those in the data source using the DataTablename. (Inherited from DbDataAdapter.) Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names.(Inherited from DbDataAdapter.) Adds or refreshes rows in the DataTable to match those in the data source using the DataTable name and the specifiedIDataReader. (Inherited from DataAdapter.) Adds or refreshes rows in a DataTable to match those in an ADO Recordset or Record object using the specifiedDataTable and ADO objects. Adds or refreshes rows in the DataSet to match those in an ADO Recordset or Record object using the specifiedDataSet, ADO object, and source table name. Adds or refreshes rows in a DataTable to match those in the data source using the specified DataTable,IDbCommand and CommandBehavior. (Inherited fromDbDataAdapter.) Adds or refreshes rows in a DataTable to match those in the data source starting at the specified record and retrieving up to the specified maximum number of records.(Inherited from DbDataAdapter.) Adds or refreshes rows in a specified range in the DataSetto match those in the data source using the DataSet andDataTable names. (Inherited from DbDataAdapter.) Adds or refreshes rows in a specified range in the collection of DataTable objects to match those in the data source.(Inherited from DataAdapter.)
Fill(DataTable)
Fill(DataSet, String)
Fill(DataTable, IDataReader)
Fill(DataTable, Object)
Adds or refreshes rows in a specified range in the DataSetto match those in the data source using the DataSet andDataTable names. (Inherited from DataAdapter.) Adds or refreshes rows in a specified range in the DataSetto match those in the data source using the DataSet andDataTable names. (Inherited from DbDataAdapter.) Adds or refreshes rows in a specified range in the DataSetto match those in the data source using the DataSet and source table names, command string, and command behavior. (Inherited from DbDataAdapter.) Adds a DataTable named "Table" to the specified DataSetand configures the schema to match that in the data source based on the specified SchemaType. (Inherited fromDbDataAdapter.) Configures the schema of the specified DataTable based on the specified SchemaType. (Inherited from DbDataAdapter.) Adds a DataTable to the specified DataSet and configures the schema to match that in the data source based upon the specified SchemaType and DataTable. (Inherited fromDbDataAdapter.) Adds a DataTable to the specified DataSet. (Inherited fromDataAdapter.) Adds a DataTable to the specified DataSet. (Inherited fromDataAdapter.) Configures the schema of the specified DataTable based on the specified SchemaType, command string, andCommandBehavior values. (Inherited from DbDataAdapter.) Adds a DataTable to the specified DataSet and configures the schema to match that in the data source based on the specified SchemaType. (Inherited from DbDataAdapter.) Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Returns a IDataParameter from one of the commands in the current
FillSchema(DataSet, SchemaType)
FillSchema(DataTable, SchemaType)
FillSchema(DataTable, SchemaType, IDataReader) FillSchema(DataSet, SchemaType, String, IDataReader) FillSchema(DataTable, SchemaType, IDbCommand, CommandBehavior)
GetBatchedParameter
batch. (Inherited from DbDataAdapter.) GetBatchedRecordsAffected Returns information about an individual update attempt within a larger batched update. (Inherited fromDbDataAdapter.) Gets the parameters set by the user when executing an SQL SELECT statement. (Inherited from DbDataAdapter.) Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited fromMarshalByRefObject.) Returns an object that represents a service provided by theComponent or by its Container. (Inherited fromComponent.) Gets the Type of the current instance. (Inherited fromObject.) Indicates whether a DataTableMappingCollection has been created. (Inherited from DataAdapter.) Initializes batching for the DbDataAdapter. (Inherited fromDbDataAdapter.) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited fromMarshalByRefObject.) Creates a shallow copy of the current Object. (Inherited from Object.) Creates a shallow copy of the current MarshalByRefObjectobject. (Inherited from MarshalByRefObject.) Invoked when an error occurs during a Fill. (Inherited fromDataAdapter.) Raises the RowUpdated event of a .NET Framework data provider. (Inherited from DbDataAdapter.) Raises the RowUpdating event of a .NET Framework data provider. (Inherited from DbDataAdapter.) Resets FillLoadOption to its default state and
GetFillParameters
GetHashCode
GetLifetimeService
GetService
GetType HasTableMappings
InitializeBatching
InitializeLifetimeService
MemberwiseClone MemberwiseClone(Boolean)
OnFillError
OnRowUpdated
OnRowUpdating
ResetFillLoadOption
causesDataAdapter.Fill to honor AcceptChangesDuringFill.(Inherited from DataAdapter.) ShouldSerializeAcceptChangesDuringFill Determines whether the AcceptChangesDuringFill property should be persisted. (Inherited from DataAdapter.) ShouldSerializeFillLoadOption Determines whether the FillLoadOption property should be persisted. (Inherited from DataAdapter.) Determines whether one or more DataTableMappingobjects exist and they should be persisted. (Inherited fromDataAdapter.) Ends batching for the DbDataAdapter. (Inherited fromDbDataAdapter.) Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited fromComponent.) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array of DataRow objects. (Inherited from DbDataAdapter.) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specifiedDataSet. (Inherited from DbDataAdapter.) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specifiedDataTable. (Inherited from DbDataAdapter.) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified array of DataRow objects. (Inherited from DbDataAdapter.) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the DataSetwith the specified DataTable name. (Inherited fromDbDataAdapter.)
ShouldSerializeTableMappings
TerminateBatching
ToString
Update(DataRow())
Update(DataSet)
Update(DataTable)
Update(DataRow(), DataTableMapping)
Update(DataSet, String)
Events
Name Disposed
Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
FillError RowUpdated
Returned when an error occurs during a fill operation. (Inherited from DataAdapter.) Occurs during Update after a command is executed against the data source. The attempt to update is made. Therefore, the event occurs.
RowUpdating Occurs during Update before a command is executed against the data source. The attempt to update is made. Therefore, the event occurs. Explicit Interface Implementations
Description For a description of this member, see ICloneable.Clone. Indicates how a source table is mapped to a dataset table.(Inherited from DataAdapter.) For a description of this member, see DeleteCommand. For a description of this member, see InsertCommand. For a description of this member, see SelectCommand.
The DataTable object provides a series of events that can be processed by an application. The following table describes DataTable events.
Event
Initialized
Description
Occurs after the EndInit method of a DataTable is called. This event is intended primarily to support design-time scenarios. Occurs after a value has been successfully changed in a DataColumn. Occurs when a value has been submitted for a DataColumn. Occurs after a DataColumn value or the RowState of a DataRow in the DataTable has been changed successfully. Occurs when a change has been submitted for a DataColumn value or the RowState of aDataRow in the DataTable. Occurs after a DataRow in the DataTable has been marked as Deleted. Occurs before a DataRow in the DataTable is marked as Deleted. Occurs after a call to the Clear method of the DataTable has successfully cleared every DataRow. Occurs after the Clear method is called but before the Clear operation begins. Occurs after a new DataRow is created by a call to the NewRow method of the DataTable. Occurs when the DataTable is Disposed. Inherited from MarshalByValueComponent.
RowChanging
TableClearing TableNewRow
Disposed
Note
Most operations that add or delete rows do not raise the ColumnChanged and ColumnChanging events. However, the ReadXml method does raise ColumnChanged and ColumnChanging events, unless theXmlReadMode is set to DiffGram or is set to Auto when the XML document being read is a DiffGram.
Caution
Data corruption can occur if data is modified in a DataSet from which the RowChanged event is raised. No exception will be raised if such data corruption occurs.
The Constraints property holds a ConstraintCollection instance. The ConstraintCollection class exposes aCollectionChanged event. This event fires when a constraint is added, modified, or removed from theConstraintCollection. The Columns property holds a DataColumnCollection instance. The DataColumnCollection class exposes aCollectionChanged event. This event fires when a DataColumn is added, modified, or removed from theDataColumnCollection. Modifications that cause the event to fire include changes to the name, type, expression or ordinal position of a column. The Tables property of a DataSet holds a DataTableCollection instance. The DataTableCollection class exposes both a CollectionChanged and a CollectionChanging event. These events fire when a DataTable is added to or removed from the DataSet. Changes to DataRows can also trigger events for an associated DataView. The DataView class exposes aListChanged event that fires when a DataColumn value changes or when the composition or sort order of the view changes. The DataRowView class exposes a PropertyChanged event that fires when an associated DataColumn value changes.
Sequence of Operations
Here is the sequence of operations that occur when a DataRow is added, modified, or deleted: 1. 2. 3. 4. 5. 6. Create the proposed record and apply any changes. Check constraints for non-expression columns. Raise the RowChanging or RowDeleting events as applicable. Set the proposed record to be the current record. Update any associated indexes. Raise ListChanged events for associated DataView objects and PropertyChanged events for associatedDataRowView objects. 7. Evaluate all expression columns, but delay checking any constraints on these columns. 8. Raise ListChanged events for associated DataView objects and PropertyChanged events for associatedDataRowView objects affected by the expression column evaluations. 9. Raise RowChanged or RowDeleted events as applicable. 10. Check constraints on expression columns.
Note
Changes to expression columns never raise DataTable events. Changes to expression columns only raiseDataView and DataRowView events. Expression columns can have dependencies on multiple other columns, and can be evaluated multiple times during a single DataRow operation. Each expression evaluation raises events, and a single DataRow operation can raise
10 Asst. Prof. Syed Faisal Ali ADO.NET extracted from MSDN
multiple ListChanged and PropertyChanged events when expression columns are affected, possibly including multiple events for the same expression column.
Caution
Do not throw a NullReferenceException within the RowChanged event handler. If a NullReferenceException is thrown within the RowChanged event of a DataTable, then the DataTable will be corrupted.
Example
The following example demonstrates how to create event handlers for the RowChanged, RowChanging,RowDeleted, RowDeleting, ColumnChanged, ColumnChanging, Tab leNewRow, TableCleared, and TableClearingevents. Each event handler displays output in the console window when it is fired. C# static void DataTableEvents() { DataTable table = new DataTable("Customers"); // Add two columns, id and name. table.Columns.Add("id", typeof(int)); table.Columns.Add("name", typeof(string)); // Set the primary key. table.Columns["id"].Unique = true; table.PrimaryKey = new DataColumn[] { table.Columns["id"] }; // Add a RowChanged event handler. table.RowChanged += new DataRowChangeEventHandler(Row_Changed); // Add a RowChanging event handler. table.RowChanging += new DataRowChangeEventHandler(Row_Changing); // Add a RowDeleted event handler. table.RowDeleted += new DataRowChangeEventHandler(Row_Deleted); // Add a RowDeleting event handler. table.RowDeleting += new DataRowChangeEventHandler(Row_Deleting); // Add a ColumnChanged event handler. table.ColumnChanged += new DataColumnChangeEventHandler(Column_Changed); // Add a ColumnChanging event handler. table.ColumnChanging += new DataColumnChangeEventHandler(Column_Changing); // Add a TableNewRow event handler. table.TableNewRow += new DataTableNewRowEventHandler(Table_NewRow);
// Add a TableCleared event handler. table.TableCleared += new DataTableClearEventHandler(Table_Cleared); // Add a TableClearing event handler. table.TableClearing += new DataTableClearEventHandler(Table_Clearing); // Add a customer. DataRow row = table.NewRow(); row["id"] = 1; row["name"] = "Customer1"; table.Rows.Add(row); table.AcceptChanges(); // Change the customer name. table.Rows[0]["name"] = "ChangedCustomer1"; // Delete the row. table.Rows[0].Delete(); // Clear the table. table.Clear(); }
private static void Row_Changed(object sender, DataRowChangeEventArgs e) { Console.WriteLine("Row_Changed Event: name={0}; action={1}", e.Row["name"], e.Action); } private static void Row_Changing(object sender, DataRowChangeEventArgs e) { Console.WriteLine("Row_Changing Event: name={0}; action={1}", e.Row["name"], e.Action); } private static void Row_Deleted(object sender, DataRowChangeEventArgs e) { Console.WriteLine("Row_Deleted Event: name={0}; action={1}", e.Row["name", DataRowVersion.Original], e.Action); } private static void Row_Deleting(object sender, DataRowChangeEventArgs e) { Console.WriteLine("Row_Deleting Event: name={0}; action={1}", e.Row["name"], e.Action); } private static void Column_Changed(object sender, DataColumnChangeEventArgs e) {
Console.WriteLine("Column_Changed Event: ColumnName={0}; RowState={1}", e.Column.ColumnName, e.Row.RowState); } private static void Column_Changing(object sender, DataColumnChangeEventArgs e) { Console.WriteLine("Column_Changing Event: ColumnName={0}; RowState={1}", e.Column.ColumnName, e.Row.RowState); } private static void Table_NewRow(object sender, DataTableNewRowEventArgs e) { Console.WriteLine("Table_NewRow Event: RowState={0}", e.Row.RowState.ToString()); } private static void Table_Cleared(object sender, DataTableClearEventArgs e) { Console.WriteLine("Table_Cleared Event: TableName={0}; Rows={1}", e.TableName, e.Table.Rows.Count.ToString()); } private static void Table_Clearing(object sender, DataTableClearEventArgs e) { Console.WriteLine("Table_Clearing Event: TableName={0}; Rows={1}", e.TableName, e.Table.Rows.Count.ToString()); }
DataSet customerOrders = new DataSet("CustomerOrders"); DataTable ordersTable = customerOrders.Tables.Add("Orders"); DataColumn pkOrderID = ordersTable.Columns.Add("OrderID", typeof(Int32)); ordersTable.Columns.Add("OrderQuantity", typeof(Int32)); ordersTable.Columns.Add("CompanyName", typeof(string)); ordersTable.PrimaryKey = new DataColumn[] { pkOrderID }; CaseSensitive
Two or more tables or relations with the same name, but different casing, can exist in a DataSet. In such cases, references by name to tables and relations are case sensitive. For example, if the DataSet dataSet contains tablesTable1 and table1, you would reference Table1 by name as dataSet.Tables["Table1"], and table1 asdataSet.Tables["table1"]. Attempting to reference either of the tables as dataSet.Tables["TABLE1"] would generate an exception. The case-sensitivity behavior does not apply if only one table or relation has a particular name. For example, if theDataSet has only Table1, you can reference it using dataSet.Tables["TABLE1"].
Note
The CaseSensitive property of the DataSet does not affect this behavior. The CaseSensitive property applies to the data in the DataSet and affects sorting, searching, filtering, enforcing constraints, and so on.
A DataRelation also has a Nested property which, when set to true, causes the rows from the child table to be nested within the associated row from the parent table when written as XML elements using WriteXml
The next example builds on the preceding example, relating four tables together and navigating those relationships. As in the previous example, CustomerID relates the Customers table to the Orders table. For each customer in theCustomers table, all the child rows in the Orders table are determined, in order to return the number of orders a particular customer has and their OrderID values. The expanded example also returns the values from the OrderDetails and Products tables. The Orders table is related to the OrderDetails table using OrderID to determine, for each customer order, what products and quantities were ordered. Because the OrderDetails table only contains the ProductID of an ordered product, OrderDetails is related to Products using ProductID in order to return the ProductName. In this relation, the Products table is the parent and the Order Details table is the child. As a result, when iterating through the OrderDetails table, GetParentRow is called to retrieve the related ProductName value. Notice that when the DataRelation is created for the Customers and Orders tables, no value is specified for thecreateConstraints flag (the default is true). This assumes that all the rows in the Orders table have a CustomerID value that exists in the parent Customers table. If a CustomerID exists in the Orders table that does not exist in theCustomers table, a ForeignKeyConstraint causes an exception to be thrown. When the child column might contain values that the parent column does not contain, set the createConstraints flag tofalse when adding the DataRelation. In the example, the createConstraints flag is set to false for the DataRelationbetween the Orders table and
the OrderDetails table. This enables the application to return all the records from theOrderDetails table and only a subset of records from the Orders table without generating a run-time exception. The expanded sample generates output in the following format. Customer ID: NORTS Order ID: 10517 Order Date: Product: Quantity: Product: Quantity: Product: Quantity: Order ID: 11057 Order Date: Product: Quantity:
4/24/1997 12:00:00 AM Filo Mix 6 Raclette Courdavault 4 Outback Lager 6 4/29/1998 12:00:00 AM Outback Lager 3
The following code example is an expanded sample where the values from the OrderDetails and Products tables are returned, with only a subset of the records in the Orders table being returned. DataRelation customerOrdersRelation = customerOrders.Relations.Add("CustOrders", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]); DataRelation orderDetailRelation = customerOrders.Relations.Add("OrderDetail", customerOrders.Tables["Orders"].Columns["OrderID"], customerOrders.Tables["OrderDetails"].Columns["OrderID"], false); DataRelation orderProductRelation = customerOrders.Relations.Add("OrderProducts", customerOrders.Tables["Products"].Columns["ProductID"], customerOrders.Tables["OrderDetails"].Columns["ProductID"]); foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows) { Console.WriteLine("Customer ID: " + custRow["CustomerID"]); foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation)) { Console.WriteLine(" Order ID: " + orderRow["OrderID"]); Console.WriteLine("\tOrder Date: " + orderRow["OrderDate"]); foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRelation)) { Console.WriteLine("\t Product: " + detailRow.GetParentRow(orderProductRelation)["ProductName"]); Console.WriteLine("\t Quantity: " + detailRow["Quantity"]); } }}