c# - Datatable vs Dataset

original title: "c# - Datatable vs Dataset"


Translate

I currently use a DataTable to get results from a database which I can use in my code.

However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method.

Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results?



Attualmente uso una DataTable per ottenere risultati da un database che posso usare nel mio codice. Tuttavia, molti esempi sul web mostrano l'uso di un DataSet e l'accesso alle tabelle tramite la raccolta ...

Questo è il riepilogo dopo la traduzione, se è necessario visualizzare la traduzione completa, fare clic sull'icona "traduci"


Tutte le risposte
  • Translate

    It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object.

    Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.


  • Translate

    One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.

    If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.


  • Translate

    in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.


  • Translate

    One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.


  • Translate

    There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.


  • Translate

    When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.


  • Translate

    A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.